Skip to main content
Back to problems
#1094
Medium Algorithms

Car pooling

Array Sorting Heap (Priority Queue) Simulation Prefix Sum
56.2% acceptance
Feb 25, 2026
4817
123
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn car_pooling(trips: Vec<Vec<i32>>, capacity: i32) -> bool {
    let mut diff = [0i32; 1001];
    for t in &trips {
      diff[t[1] as usize] += t[0];
      diff[t[2] as usize] -= t[0];
    }
    let mut cur = 0i32;
    for &d in &diff {
      cur += d;
      if cur > capacity { return false; }
    }
    true
  }
}