KatInterview

Fewest Drivers to Cover Every Trip Without Overlap

Greedy & IntervalsAuto-graded · 18 test cases
MediumAuto-gradedGreedy & Intervalsintervalssweep-lineheap

Last updated

Find the fewest drivers needed to serve all trips given [start, end) times, which reduces to the peak number of simultaneous trips and tests sweep-line or heap handling of boundaries.

A ride-hailing platform has a list of scheduled trips. Each trip is a pair [start, end] of integer timestamps. A driver can work on only one trip at a time, and every trip must be handled by exactly one driver.

Return the minimum number of drivers needed to serve all trips so that no driver is on two trips at the same moment.

Rules

  • A trip occupies the half-open time span [start, end). The driver is busy from start up to, but not including, end.
  • If one trip ends at time t and another starts at time t, the same driver can take both. For example, [1, 5] and [5, 8] need only one driver.
  • A trip with start == end occupies no time, so it never forces an extra driver and contributes nothing to the answer.
  • The trips may appear in any order.
  • If there are no trips, return 0.

Input

  • trips: a list of [start, end] pairs of integers, with start <= end.

Output

  • An integer: the smallest number of drivers that can cover all trips.

Constraints

  • 0 <= len(trips) <= 10^5
  • Each trip has exactly two integers, start and end, with start <= end.
  • Timestamps are integers and may be any size that fits in a standard integer.
  • The list is not guaranteed to be sorted.

Examples

Example 1

Input: min_drivers_needed([[1, 4], [2, 5], [5, 7]])

Output: 2

Example 2

Input: min_drivers_needed([[1, 3], [3, 6], [2, 4]])

Output: 2

Example 3

Input: min_drivers_needed([])

Output: 0

Hints

Hint 1

Each driver handles one trip at a time, so the answer can never be lower than the largest number of trips happening at the same instant. Think about whether that number is also enough.

Hint 2

Turn every trip into two events, one when it begins and one when it finishes, then process events in time order while keeping a running count of active trips.

Hint 3

Decide what happens when a finish and a start share the same timestamp. Under the half-open rule the finish must be handled first, which falls out of sorting (time, delta) pairs with -1 for finishes and +1 for starts.