Minimum Speed to Arrive on Time — LeetCode 1870 Python Solution
- Problem
- #1870
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n and M are the number of train trips and the upper bound of the speed, respectively |
| Space | O(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.