The Latest Time to Catch a Bus

You are given a 0-indexed integer array buses of length n, where buses[i] represents the departure time of the i^th bus. You are also given a 0-indexed integer array passengers of length m, where passengers[j] represents the arrival time of the j^th passenger. All bus departure times are unique. All passenger arrival times are unique.

You are given an integer capacity, which represents the maximum number of passengers that can get on each bus.

When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x, and the bus is not full. Passengers with the earliest arrival times get on the bus first.

More formally when a bus arrives, either:

  • If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or
  • The capacity passengers with the earliest arrival times will get on the bus.

Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger.

Note: The arrays buses and passengers are not necessarily sorted.

Example 1
Inputbuses = [10,20], passengers = [2,17,18,19], capacity = 2
Output16
If you arrive at time 16, the first bus takes the 0^th passenger, and the second bus takes you and the 1^st passenger; you cannot arrive at time 17 because that is another passenger's arrival time.
Example 2
Inputbuses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2
Output20
If you arrive at time 20, the first two buses take earlier passengers, and you can catch the third bus before any later arrival would lose the seat to the 6^th passenger.

Constraints

  • n == buses.length
  • m == passengers.length
  • 1 <= n, m, capacity <= 10^5
  • 2 <= buses[i], passengers[i] <= 10^9
  • Each element in buses is unique.
  • Each element in passengers is unique.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate