Validate carpool capacity
Company: Meta
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of interval-based resource accounting and algorithmic reasoning with cumulative constraints, assessing skills in processing time-bound events and managing capacity limits.
Constraints
- 1 <= trips.length <= 1000
- trips[i].length == 3
- 1 <= numPassengers <= 100
- 0 <= start < end <= 1000
- 1 <= capacity <= 100000
Examples
Input: ([[2, 1, 5], [3, 3, 7]], 4)
Expected Output: False
Explanation: Between km 3 and 5, both trips overlap: 2 + 3 = 5 passengers aboard, exceeding capacity 4 -> false.
Input: ([[2, 1, 5], [3, 3, 7]], 5)
Expected Output: True
Explanation: Peak occupancy is 5 (km 3-5), which equals capacity 5, so it never exceeds -> true.
Input: ([[2, 1, 5], [3, 5, 7]], 3)
Expected Output: True
Explanation: The first trip ends at km 5 exactly when the second begins, so they never overlap; max aboard is 3 = capacity -> true.
Input: ([], 0)
Expected Output: True
Explanation: No trips means no passengers are ever aboard, so capacity is never exceeded -> true.
Input: ([[5, 0, 1000]], 5)
Expected Output: True
Explanation: A single full-route trip of 5 passengers exactly fills capacity 5 -> true.
Input: ([[6, 0, 1000]], 5)
Expected Output: False
Explanation: A single trip of 6 passengers exceeds capacity 5 from the very start -> false.
Input: ([[3, 2, 7], [3, 7, 9], [8, 3, 9]], 11)
Expected Output: True
Explanation: Peak occupancy: km 3-7 has trips 1 and 3 = 3 + 8 = 11; the second trip starts at km 7 as the first drops off, keeping max at 11 = capacity -> true.
Hints
- Think of each trip as +numPassengers at `start` and -numPassengers at `end`. The occupancy only changes at these event points.
- Use a difference array indexed by location: add passengers at `start`, subtract them at `end`. A prefix sum over it gives the number of passengers aboard at every location.
- Sweep the prefix sum from left to right; if it ever exceeds `capacity`, return false. Because drop-off happens exactly at `end`, subtracting at index `end` (not end+1) correctly frees the seat before any same-location pickup.