The Latest Time to Catch a Bus — LeetCode 2332 Python Solution
- Problem
- #2332
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array buses of length n, where buses[i] represents the departure time of the ith bus. You are also given a 0-indexed integer array passengers of length m, where passengers[j] represents the arrival time of the jth passenger.
Example
- Input
- buses = [10,20], passengers = [2,17,18,19], capacity = 2
- Output
- 16
- Explanation
- Suppose you arrive at time 16.
Python solution
class Solution:
def latestTimeCatchTheBus(
self, buses: List[int], passengers: List[int], capacity: int
) -> int:
buses.sort()
passengers.sort()
j = 0
for t in buses:
c = capacity
while c and j < len(passengers) and passengers[j] <= t:
c, j = c - 1, j + 1
j -= 1
ans = buses[-1] if c else passengers[j]
while ~j and passengers[j] == ans:
ans, j = ans - 1, j - 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n + m \times \log m) |
| Space | O(\log n + \log m) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 2332. The Latest Time to Catch a Bus is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2332. The Latest Time to Catch a Bus?
- LeetCode 2332. The Latest Time to Catch a Bus is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2332. The Latest Time to Catch a Bus?
- The Python solution on this page runs in O(n \times \log n + m \times \log m).
- What is the space complexity of LeetCode 2332. The Latest Time to Catch a Bus?
- The Python solution on this page uses O(\log n + \log m) auxiliary space.
- What topics does LeetCode 2332. The Latest Time to Catch a Bus cover?
- LeetCode 2332. The Latest Time to Catch a Bus is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.