#1870

Minimum Speed to Arrive on Time

Medium
ArrayBinary SearchBinary SearchGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log m)Space O(1)

Instead of checking every speed, we can use binary search to efficiently find the minimum speed that allows us to arrive on time. This reduces the number of checks significantly.

⚙️

Algorithm

6 steps
  1. 1Step 1: Set low to 1 and high to 10^7.
  2. 2Step 2: While low is less than or equal to high, calculate mid as the average of low and high.
  3. 3Step 3: Calculate the total time taken for the current mid speed.
  4. 4Step 4: If the total time is less than or equal to hour, update the answer and reduce high to mid - 1.
  5. 5Step 5: If total time is greater than hour, increase low to mid + 1.
  6. 6Step 6: Return the answer.
solution.py16 lines
1def minSpeedOnTime(dist, hour):
2    low, high = 1, 10**7
3    answer = -1
4    while low <= high:
5        mid = (low + high) // 2
6        total_time = 0
7        for i in range(len(dist)):
8            total_time += dist[i] / mid
9            if i < len(dist) - 1:
10                total_time = int(total_time) + (total_time % 1 > 0)
11        if total_time <= hour:
12            answer = mid
13            high = mid - 1
14        else:
15            low = mid + 1
16    return answer

Complexity note: The binary search runs in log m time (where m is the maximum speed), and for each speed, we traverse the distances array, leading to O(n log m) complexity.

  • 1Binary search helps efficiently narrow down the minimum speed.
  • 2Calculating total time correctly is crucial to determine if we arrive on time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.