LeetCode 2332: The Latest Time to Catch a Bus Solution
Master LeetCode problem 2332 (The Latest Time to Catch a Bus), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2332. The Latest Time to Catch a Bus
Problem Explanation
Explanation:
To solve this problem, we need to find the latest time a passenger can arrive at the bus station to catch a bus. We can simulate the process of passengers arriving and buses departing to determine this time.
- We first sort both the arrays
busesandpassengersin ascending order. - Initialize a variable
timeto 0 to represent the current time. - Iterate through the buses and passengers simultaneously.
- For each bus, while there are passengers waiting and the bus is not full, we check if the next passenger in line can catch the bus at the current time.
- If the passenger can catch the bus, we update the time to the maximum of the current time and the passenger's arrival time.
- Return the latest time as the result.
Time Complexity:
The time complexity of this approach is O(n + m), where n is the number of buses and m is the number of passengers.
Space Complexity:
The space complexity is O(1) as we are not using any extra space apart from a few variables.
Solution Code
import java.util.Arrays;
class Solution {
public int latestTimeToCatchBus(int[] buses, int[] passengers, int capacity) {
Arrays.sort(buses);
Arrays.sort(passengers);
int time = 0;
int passengerIdx = 0;
for (int bus : buses) {
while (passengerIdx < passengers.length && passengers[passengerIdx] <= bus && passengerIdx < capacity) {
time = Math.max(time, passengers[passengerIdx]);
passengerIdx++;
}
}
return time;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2332 (The Latest Time to Catch a Bus)?
This page provides optimized solutions for LeetCode problem 2332 (The Latest Time to Catch a Bus) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2332 (The Latest Time to Catch a Bus)?
The time complexity for LeetCode 2332 (The Latest Time to Catch a Bus) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2332 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2332 in Java, C++, or Python.