Minimum Speed to Arrive on Time — LeetCode 1870 Python Solution

MediumArrayBinary Search
Problem
#1870
Reading time
3 min

The problem

You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order.

Example

Input
dist = [1,3,2], hour = 6
Output
1
Explanation
At speed 1:

Python solution

Python
class Solution:
    def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
        def check(v: int) -> bool:
            s = 0
            for i, d in enumerate(dist):
                t = d / v
                s += t if i == len(dist) - 1 else ceil(t)
            return s <= hour

        if len(dist) > ceil(hour):
            return -1
        r = 10**7 + 1
        ans = bisect_left(range(1, r), True, key=check) + 1
        return -1 if ans == r else ans

Complexity

MeasureComplexity
TimeO(n \times \log M), where n and M are the number of train trips and the upper bound of the speed, respectively
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1870. Minimum Speed to Arrive on Time is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1870. Minimum Speed to Arrive on Time?
LeetCode 1870. Minimum Speed to Arrive on Time is rated Medium on LeetCode.
What is the time complexity of LeetCode 1870. Minimum Speed to Arrive on Time?
The Python solution on this page runs in O(n \times \log M), where n and M are the number of train trips and the upper bound of the speed, respectively.
What is the space complexity of LeetCode 1870. Minimum Speed to Arrive on Time?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1870. Minimum Speed to Arrive on Time cover?
LeetCode 1870. Minimum Speed to Arrive on Time is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview