Bird
Raised Fist0
Interview PrepintervalsmediumAmazonGoogleFacebook

Car Pooling

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem

Imagine you are managing a carpool service where multiple groups of passengers get on and off at different locations along a route. You need to ensure the car's capacity is never exceeded at any point.

You are driving a vehicle that can hold a fixed number of passengers (capacity). Given a list of trips, where each trip is represented as [num_passengers, start_location, end_location], determine if it is possible to pick up and drop off all passengers for all the given trips without exceeding the vehicle's capacity at any point. The vehicle only moves in one direction along a route from location 0 to location 1000.

1 ≤ number of trips ≤ 10^50 ≤ start_location < end_location ≤ 10001 ≤ num_passengers ≤ 10001 ≤ capacity ≤ 10^5
Edge cases: Single trip with passengers equal to capacity → should return trueTrips with no overlapping intervals → should return trueTrips where passengers get off exactly when others get on → should return true
</>
IDE
def carPooling(trips: list[list[int]], capacity: int) -> bool:public boolean carPooling(int[][] trips, int capacity)bool carPooling(vector<vector<int>>& trips, int capacity)function carPooling(trips, capacity)
def carPooling(trips, capacity):
    # Write your solution here
    pass
class Solution {
    public boolean carPooling(int[][] trips, int capacity) {
        // Write your solution here
        return false;
    }
}
#include <vector>
using namespace std;

bool carPooling(vector<vector<int>>& trips, int capacity) {
    // Write your solution here
    return false;
}
function carPooling(trips, capacity) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: trueIgnoring overlapping intervals and summing passengers incorrectly, causing capacity overflow to be missed.Implement event sorting and sweep line to accumulate passenger counts at each location and compare with capacity.
Wrong: falseOff-by-one error in interval handling, counting passengers at end location incorrectly.Process drop-offs before pickups at the same location to avoid overcounting passengers.
Wrong: trueTreating trips as unbounded or reusing passengers multiple times (0/1 vs unbounded confusion).Count passengers only once per trip interval; do not reuse or multiply counts.
Wrong: falseIncorrect handling of empty trips input, returning false or error instead of true.Return true immediately if trips list is empty.
Wrong: TLEBrute force simulation of all locations for large inputs causing time limit exceeded.Use event sorting and sweep line approach with O(n log n) complexity.
Test Cases
t1_01basic
Input{"trips":[[2,1,5],[3,3,7]],"capacity":4}
Expectedfalse

Between locations 3 and 5, total passengers would be 2 + 3 = 5, which exceeds capacity 4.

t1_02basic
Input{"trips":[[2,1,5],[3,3,7]],"capacity":5}
Expectedtrue

Capacity 5 is sufficient for overlapping passengers 2 + 3 = 5 between locations 3 and 5.

t2_01edge
Input{"trips":[],"capacity":10}
Expectedtrue

No trips means no passengers, so capacity is never exceeded.

t2_02edge
Input{"trips":[[5,0,10]],"capacity":5}
Expectedtrue

Single trip with passengers equal to capacity should return true.

t2_03edge
Input{"trips":[[2,1,3],[3,3,5]],"capacity":3}
Expectedtrue

Passengers get off exactly when others get on; capacity never exceeded.

t3_01corner
Input{"trips":[[2,1,5],[3,2,6],[1,4,7]],"capacity":5}
Expectedfalse

Greedy approach picking earliest trips first fails; total passengers exceed capacity between locations 4 and 5.

t3_02corner
Input{"trips":[[1,0,2],[1,1,3],[1,2,4]],"capacity":1}
Expectedfalse

Confusing 0/1 vs unbounded: passengers cannot be reused multiple times; capacity exceeded between locations 1 and 2.

t3_03corner
Input{"trips":[[3,0,5],[2,5,10]],"capacity":3}
Expectedtrue

Off-by-one error test: passengers get off exactly when others get on; capacity never exceeded.

t4_01performance
Input{"trips":[[1000,0,500],[1000,500,1000]],"capacity":1000}
⏱ Performance - must finish in 2000ms

n=2 trips with max passengers and max location range; O(n log n) sweep line approach must complete within 2s.

Practice

(1/5)
1. Consider the following Python code that determines if a person can attend all meetings given a list of intervals. What is the return value when the input is [[7,10],[2,4]]?
from typing import List

def can_attend_meetings(intervals: List[List[int]]) -> bool:
    intervals.sort(key=lambda x: x[0])
    end = float('-inf')
    for interval in intervals:
        if interval[0] < end:
            return False
        end = interval[1]
    return True

print(can_attend_meetings([[7,10],[2,4]]))
easy
A. None
B. False
C. Raises an exception
D. True

Solution

  1. Step 1: Sort intervals by start time

    Input [[7,10],[2,4]] becomes [[2,4],[7,10]].
  2. Step 2: Iterate and check overlaps

    Initialize end = -inf. First interval start=2 > -inf, update end=4. Second interval start=7 > 4, update end=10. No overlaps found, return True.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Intervals sorted and no overlaps detected [OK]
Hint: Sort then check if current start < previous end [OK]
Common Mistakes:
  • Confusing return value due to unsorted intervals
2. Consider the following Python code that merges intervals in-place after sorting. Given the input intervals = [[1,4],[2,5],[7,9]], what is the returned list after the function completes?
easy
A. [[1,5],[7,9]]
B. [[1,4],[2,5],[7,9]]
C. [[1,5],[2,5],[7,9]]
D. [[1,4],[7,9]]

Solution

  1. Step 1: Sort intervals by start time.

    Input is already sorted: [[1,4],[2,5],[7,9]].
  2. Step 2: Merge intervals in one pass.

    Compare [2,5] with [1,4]: overlap since 2 <= 4, merge to [1,5]. Then compare [7,9] with [1,5]: no overlap, move index forward and assign [7,9]. Final intervals: [[1,5],[7,9]].
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Overlapping intervals merged correctly, non-overlapping preserved. [OK]
Hint: Check if current start ≤ last merged end to merge [OK]
Common Mistakes:
  • Returning original intervals without merging
  • Off-by-one slicing errors
3. What is the time complexity of the addNum operation in the optimal balanced tree approach for maintaining disjoint intervals, assuming there are n intervals stored?
medium
A. O(n) because intervals need to be scanned linearly for merging
B. O(log n) due to binary search and limited merging operations
C. O(n log n) because each insertion requires sorting intervals
D. O(1) since insertion is always at the end or start

Solution

  1. Step 1: Identify main operations in addNum

    addNum uses binary search (bisect_left) to find insertion index in O(log n).
  2. Step 2: Analyze merging cost

    Merging involves at most constant number of interval merges (left, right, or both), so O(1) extra work.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Binary search dominates, merges are constant time [OK]
Hint: Binary search + constant merges -> O(log n) [OK]
Common Mistakes:
  • Assuming linear scan for merging
  • Confusing sorting cost per insertion
  • Ignoring constant merge steps
4. What is the time complexity of the optimal algorithm that determines if a person can attend all meetings given n intervals, where the algorithm sorts intervals by start time and then checks for overlaps in a single pass?
medium
A. O(n) because we only scan the intervals once after sorting
B. O(n^2) because each interval is compared with all others for overlaps
C. O(n log n) due to sorting the intervals by start time
D. O(log n) because sorting can be done in logarithmic time

Solution

  1. Step 1: Identify sorting cost

    Sorting n intervals by start time takes O(n log n) time.
  2. Step 2: Identify overlap check cost

    Single pass to check overlaps is O(n), which is dominated by sorting.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sorting dominates total time complexity [OK]
Hint: Sorting dominates complexity -> O(n log n) [OK]
Common Mistakes:
  • Confusing single pass check as O(n log n)
  • Assuming nested loops cause O(n^2) here
5. The following code attempts to find the maximum number of non-overlapping intervals. Which line contains a subtle bug that can cause incorrect results on some inputs?
def max_non_overlapping_intervals(intervals):
    intervals.sort(key=lambda x: x[0])
    removals = 0
    last_end = intervals[0][1]
    for i in range(1, len(intervals)):
        if intervals[i][0] <= last_end:
            removals += 1
            last_end = min(last_end, intervals[i][1])
        else:
            last_end = intervals[i][1]
    return len(intervals) - removals
medium
A. Line 9: Updating last_end to intervals[i][1] when no overlap
B. Line 2: Sorting intervals by start time instead of end time
C. Line 7: Updating last_end to min(last_end, intervals[i][1]) inside overlap condition
D. Line 5: Using '<=' instead of '<' in the overlap condition

Solution

  1. Step 1: Understand overlap condition

    Intervals that start exactly at last_end do not overlap and should be allowed.
  2. Step 2: Identify incorrect operator

    Using '<=' causes intervals starting exactly at last_end to be considered overlapping, reducing count incorrectly.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Change '<=' to '<' fixes the bug [OK]
Hint: Overlap check must use strict less than, not less or equal [OK]
Common Mistakes:
  • Confusing inclusive vs exclusive overlap conditions
  • Sorting by start time is allowed but less optimal
  • Incorrect last_end updates