Leetcode #2332: The Latest Time to Catch a Bus
In this guide, we solve Leetcode #2332 The Latest Time to Catch a Bus in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Two Pointers, Binary Search, Sorting
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: buses = [10,20], passengers = [2,17,18,19], capacity = 2
Output: 16
Explanation: Suppose you arrive at time 16.
At time 10, the first bus departs with the 0th passenger.
At time 20, the second bus departs with you and the 1st passenger.
Note that you may not arrive at the same time as another passenger, which is why you must arrive before the 1st passenger to catch the bus.
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 ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.