Katkat

Can one car serve all riders?

UberData Scientist · Technical Screen

Last updated

This problem tests your ability to determine if a single resource (a car) can accommodate a series of scheduled tasks without overlap, requiring efficient sorting and comparison techniques.

Problem Statement

You are given a list of ride requests, where each request is represented as a tuple (start_time, end_time). A single driver starts their shift at time 0 and can only serve one rider at a time. The driver is available to pick up a new rider immediately after completing the previous ride (i.e., if one ride ends at t, the next can start at t).

Given a list of rides, return True if a single driver can complete all the requested rides without any schedule conflicts, and False otherwise.

Function Signature

def can_serve_all(rides: List[Tuple[int, int]]) -> bool:

Constraints

  • 0 <= len(rides) <= 10^5
  • 0 <= start_time < end_time <= 10^9

Examples

Example 1: Input: rides = [(1, 3), (5, 7), (3, 4)] Output: True Explanation: The rides can be sorted by start time: (1, 3), (3, 4), (5, 7). Since each ride ends at or before the next begins, the driver can finish all of them.

Example 2: Input: rides = [(1, 5), (4, 6)] Output: False Explanation: The ride ending at 5 conflicts with the ride starting at 4.

Edge Cases

  • Empty list of rides should return True.
  • Rides that start exactly when the previous ride ends are valid.

Hints

Hint 1

Consider how sorting the rides based on their start times simplifies the task of checking for overlaps.

Hint 2

Once the list is sorted, you only need to compare the end time of the current ride with the start time of the subsequent ride.

Hint 3

If you find any instance where `current_end > next_start`, you have identified a conflict.

Follow-up questions

  • If you had to determine the minimum number of cars required to serve all rides, how would your approach change?
  • How would you modify your algorithm if there was a mandatory 'buffer time' of 5 minutes required between the end of one ride and the start of the next?
  • What is the time and space complexity of your sorting-based solution?