Leetcode 2332: The Latest Time to Catch a Bus

grid47
grid47
Exploring patterns and algorithms
Mar 18, 2024 7 min read

You are given two arrays representing bus departure times and passenger arrival times, along with the maximum capacity of each bus. The task is to determine the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger.
Problem
Approach
Steps
Complexity
Input: The input consists of three items: an array of bus departure times, an array of passenger arrival times, and an integer representing the capacity of each bus.
Example: buses = [10, 20], passengers = [2, 17, 18, 19], capacity = 2
Constraints:
• n == buses.length
• m == passengers.length
• 1 <= n, m, capacity <= 10^5
• 2 <= buses[i], passengers[i] <= 10^9
• All elements in buses and passengers are unique.
Output: Return the latest possible time you can arrive at the bus station and still catch a bus.
Example: 16
Constraints:
Goal: We need to find the latest time you can arrive at the bus station without missing a bus and without arriving at the same time as another passenger.
Steps:
• Sort the buses and passengers arrays.
• For each bus, board passengers based on arrival times and capacity.
• Determine the latest possible time you can arrive at the bus station and still catch a bus.
Goal: Ensure the bus departure times and passenger arrival times are handled correctly within the provided constraints.
Steps:
• The buses and passengers arrays are not necessarily sorted.
• Each bus and passenger time is unique.
Assumptions:
• All bus departure times are unique.
• All passenger arrival times are unique.
Input: If buses = [10, 20] and passengers = [2, 17, 18, 19], and capacity = 2, arriving at time 16 ensures you catch the second bus.
Explanation: At time 10, the first bus departs with the 0th passenger. At time 20, the second bus departs with you and the 1st passenger.

Input: For buses = [20, 30, 10], passengers = [19, 13, 26, 4, 25, 11, 21], and capacity = 2, arriving at time 20 ensures you catch the third bus.
Explanation: At time 10, the first bus departs with the 3rd passenger. At time 20, the second bus departs with the 5th and 1st passengers. At time 30, the third bus departs with the 0th passenger and you.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus