Similar Problems

Similar Problems not available

Minimum Speed To Arrive On Time - Leetcode Solution

Companies:

LeetCode:  Minimum Speed To Arrive On Time Leetcode Solution

Difficulty: Medium

Topics: binary-search array  

Problem Statement: Given the distance between two cities and the average speed you need to travel, calculate the minimum speed required to arrive on time. You are given the arrival time in seconds and the distance in meters.

Solution: To solve this problem, we are going to use binary search. We are going to search for the minimum speed required to arrive on time. We are going to use the following steps.

  1. Let’s define our boundaries for the binary search. The lower bound is 0 meters/second, and the upper bound is the distance divided by the arrival time in seconds. If we travel at a speed greater than this, we will arrive early.

  2. We set the mid-point to be the average of the upper and lower bounds. We then calculate how long it will take to travel the distance at this speed. If the time taken is less than the arrival time, we need to increase the speed. We know that the minimum speed required is greater than the current mid-point. We set the new lower bound to the current mid-point.

  3. If the time taken is greater than the arrival time, we need to decrease the speed. We know that the minimum speed required is less than the current mid-point. We set the new upper bound to the current mid-point.

  4. We keep repeating the above steps until the upper bound is less than or equal to the lower bound. At this point, we have found the minimum speed required to arrive on time. We return this speed as the answer.

Pseudo Code:

  1. Initialize lower bound lb = 0 and upper bound ub = distance / arrivalTime
  2. While ub > lb: a. Initialize mid = (lb + ub) / 2 b. Initialize time = distance / mid c. If time > arrivalTime: i. Update lb = mid d. Else if time < arrivalTime: i. Update ub = mid e. Else: i. Return mid
  3. Return ub

Time and Space Complexity:

The time complexity of this solution is O(log(distance)) because the binary search reduces the search space by half each time.

The space complexity is O(1) because we are only using a few variables to store the lower and upper bounds, mid-point, and arrival time.

Conclusion:

In this problem, we used binary search to find the minimum speed required to arrive on time. We used the time taken to travel the distance at a given speed to determine if we need to increase or decrease the speed. We kept repeating this process until we found the minimum speed required.

Minimum Speed To Arrive On Time Solution Code

1