Car Pooling solution explained

Car Pooling asks whether one car with a fixed number of seats can serve every ride on a one-way road, where each ride says how many people get on, where they board and where they leave. Turn every ride into two events, a gain at the pickup and a loss at the drop-off, then walk the events in road order with a running total. The car is fine as long as that total never goes above the seat count; sorting makes it O(n log n), and a bucket per road marker makes it linear when the markers are small.

By Published 9 min read

The problem in plain words

A car with a set number of passenger seats drives along a straight road in one direction and never turns back. Points on the road are whole numbers counted from the start. You are handed a list of rides. Each ride is a group: a number of people, the point where the whole group gets in, and a later point where the whole group gets out. Decide whether the car can carry every group without ever having more people inside than it has seats. Return true or false.

Rides written for this page, shown as [riders, pickup, drop-off]
SeatsRidesAnswerWhy
4[2, 1, 4], [3, 2, 6]falseBetween points 2 and 4 both groups are inside: 5 people
3[2, 1, 4], [3, 4, 6]trueThe first group leaves at 4 just as the second boards
5[3, 0, 5], [2, 1, 3], [1, 3, 7]trueThe busiest stretch, from 1 to 3, holds exactly 5
4[3, 0, 5], [2, 1, 3], [1, 3, 7]falseSame rides, one seat fewer, and the stretch from 1 to 3 overflows
Rides written for this page, shown as [riders, pickup, drop-off]. Scroll sideways on a small screen.

The second row is the one to ask about before writing anything. If a group gets out at point 4, is its seat free for someone getting in at point 4? In the usual version, yes: a ride covers the stretch from its pickup up to, but not including, its drop-off. Say that out loud and confirm it, because it decides how you break ties later.

What the interviewer is looking for

Underneath the story, this is a capacity check over overlapping ranges. The interviewer wants to see you stop thinking about rides and start thinking about moments where the load changes. Strong candidates notice that the number of people in the car only goes up at a pickup, so the peak must happen at one of those points, and that a running sum over sorted changes finds it in one pass. They also check that you handle the shared point correctly without being told, and that you can say when a bucket array beats sorting and when it does not.

Brute force: check the load at every pickup

Since the load only rises when a group boards, it is enough to look at each pickup point and add up every group that is inside the car at that moment. A group is inside at point x when its pickup is at or before x and its drop-off is strictly after x. With n rides, that is n checks of n rides each, so O(n²) time and O(1) extra space. It is easy to get right, which makes it a good reference to test faster versions against.

def fits_slow(rides, seats):
    # The load can only rise at a pickup point, so check each one.
    for _, start, _ in rides:
        on_board = sum(n for n, a, b in rides if a <= start < b)
        if on_board > seats:
            return False
    return True
Python: count the riders on board at each pickup point. Quadratic, used as the checker.

Notice the comparison a <= start < b. The strict less-than on the drop-off side is the shared-point rule written as code: a group leaving at point 4 is not counted at point 4.

Faster: turn rides into load changes

Instead of asking who is in the car at each point, record how the load changes. A ride of k people from a to b adds k at a and removes k at b. If you apply those changes in road order and keep a running total, the total at any moment is exactly the number of people inside. The question then becomes whether that running total ever passes the seat count.

Version 1: one bucket per road marker

When the points are small whole numbers, make an array with one slot per marker. Add each group at its pickup slot and subtract it at its drop-off slot. Then sweep the array from left to right, adding as you go. This is the difference array trick. Both the gain and the loss for a point land in the same slot, so the shared-point rule takes care of itself: the departing group and the arriving group cancel before the check happens.

def fits_by_marker(rides, seats):
    if not rides:
        return True
    last = max(b for _, _, b in rides)
    change = [0] * (last + 1)
    for riders, start, end in rides:
        change[start] += riders
        change[end] -= riders
    load = 0
    for delta in change:
        load += delta
        if load > seats:
            return False
    return True
Python: a difference array over road markers. O(n + L) time and O(L) space.

The cost depends on L, the largest marker, not only on the number of rides. If an interviewer says markers can be in the billions, the array is out, and you need the next version.

Version 2: sort the events

Make a list of pairs (point, change): one positive pair per pickup and one negative pair per drop-off. Sort it by point. At equal points, the drop-off has to come first, otherwise you briefly count the departing group and the arriving group together and report a false overflow. In Python, sorting the tuples does this for free, because a negative change sorts before a positive one at the same point. In JavaScript you have to write that tie-break into the comparator yourself.

def fits_by_events(rides, seats):
    events = []
    for riders, start, end in rides:
        events.append((start, riders))
        events.append((end, -riders))
    events.sort()          # at a tie, the negative drop-off sorts first
    load = 0
    for _, delta in events:
        load += delta
        if load > seats:
            return False
    return True
Python: sorted events with a running load. Works for any range of positions.
function fitsInCar(rides, seats) {
  const events = [];
  for (const [riders, start, end] of rides) {
    events.push([start, riders], [end, -riders]);
  }
  // Earlier point first; at the same point, drop-offs (negative) first.
  events.sort((p, q) => p[0] - q[0] || p[1] - q[1]);
  let load = 0;
  for (const [, delta] of events) {
    load += delta;
    if (load > seats) return false;
  }
  return true;
}
JavaScript: the same sweep with an explicit tie-break in the comparator

There is a third way you may see: sort rides by pickup and keep a min-heap of drop-off points for the groups still in the car. Before each new group boards, pop every group whose drop-off is at or before the new pickup. It is also O(n log n). The event sweep is shorter to write and easier to explain, so lead with it and mention the heap only if asked.

Cost of each approach

n rides, L the largest road marker
ApproachTimeExtra spaceWhen to use it
Check every pickupO(n²)O(1)As a reference, or for a handful of rides
Bucket per marker (difference array)O(n + L)O(L)Markers are small whole numbers
Sorted eventsO(n log n)O(n)Markers are large, sparse or not integers
Sort by pickup plus a heap of drop-offsO(n log n)O(n)When you also need to know which groups are aboard
n rides, L the largest road marker. Scroll sideways on a small screen.

Edge cases to test

  • No rides at all: the answer is true for any seat count.
  • One ride whose group exactly equals the seat count: true. One more person: false.
  • A drop-off and a pickup at the same point, as in the second table row: the seat is reused, so this must not overflow.
  • Several groups boarding at the same point: they all count at once.
  • A ride that starts at point 0: the bucket array needs index 0, which it has.
  • A group that by itself is larger than the car: the very first event pushes the load over, so the answer is false.

Mistakes that cost points

  • Putting pickups before drop-offs at the same point. The sweep then sees both groups inside at once and wrongly returns false.
  • Marking every point from pickup to drop-off inclusive. That counts the departing group one point too long and also slows the brute force to O(n times L).
  • Sizing the bucket array by the number of rides instead of the largest drop-off point, which leads to an index error.
  • Checking the load only at the end of the sweep. The question is about the peak, so compare after every change.
  • Sorting events by point only in a language whose sort gives no order for ties. Write the tie-break explicitly.

Follow-up questions

  • What is the smallest car that works? Run the same sweep but track the highest load instead of comparing with a limit. The peak is the answer.
  • Which stretch is the busiest? Record the point where the running load reaches its peak and the next event point after it.
  • Rides arrive one at a time and you must accept or refuse each one. You now need range updates and range maximums, which points toward a segment tree. Saying so, with the reason, is usually enough in a first round.
  • The car can drive both ways. The single sweep no longer models it; split the trip into one-way legs, or ask whether the interviewer means a loop route.

How to explain it out loud

Fictional example

Getting from rides to a running total
Candidate
Before I start: if one group gets out at point 4 and another gets in at 4, can they share the seat? I will assume yes.
Interviewer
Yes, that's right.
Candidate
Then I don't care about rides as ranges. I care about the points where the head count changes: plus k at a pickup, minus k at a drop-off.
Candidate
If I sort those changes by position, with drop-offs first on a tie, a running sum tells me how full the car is everywhere. If it ever passes the seat count, I return false.
Interviewer
Can you avoid the sort?
Candidate
If the points are small integers, yes. One slot per point, add and subtract, then sweep. That's linear in the rides plus the length of the road.

Car Pooling belongs with the interval problems where the question is how much overlaps at once. Merge Intervals sorts ranges and fuses the ones that touch, and its meeting-rooms follow-up asks the same peak question as this page. My Calendar I flips it around: bookings arrive one by one and any overlap at all is refused. For something completely different from this batch, Design Twitter is a class design with a merge of sorted lists, and Detonate the Maximum Bombs builds a graph from geometry.

Rehearsing it with Natively

The tie at a shared point is the part interviewers poke at, so practice explaining it before you need to. On a Mac or Windows computer, Natively can read a ride list like this one from a screenshot during a practice session, suggest the event sweep and the drop-off-first ordering, and transcribe your mock answer, which lets you check afterward whether you asked about the shared point at the start or found it by accident. More about this on the coding interview helper page.

Questions people ask

How do you solve Car Pooling?

Turn each ride into a gain of its riders at the pickup point and a loss at the drop-off point. Apply the changes in road order with a running total and return false the moment it passes the seat count.

Should drop-offs or pickups come first at the same point?

Drop-offs. A group leaving at a point frees its seats for a group boarding at that same point, so process the negative change first or you will report an overflow that never happens.

Is Car Pooling a difference array problem?

It can be. When road points are small whole numbers, add riders at the pickup slot, subtract at the drop-off slot and sweep the array. That runs in O(n + L), where L is the last point.

What is the time complexity of Car Pooling?

O(n log n) with sorted events, which works for any positions. O(n + L) with one bucket per road marker when markers are small. The check-every-pickup brute force is O(n²).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP