Car Fleet solution explained
Car Fleet is solved by sorting the cars from closest to the finish to farthest, computing how long each would take alone, and counting a new fleet only when a car would arrive strictly later than the fleet just ahead of it. Any car that would arrive sooner or at the same time gets stuck behind that fleet and joins it. Sorting makes it O(n log n).
By Evin JohnPublished 8 min read
The setup in plain words
Several cars drive along a single-lane road toward a destination at a known distance. Each car starts at its own position and drives at its own constant speed. Nobody can overtake. When a faster car catches a slower one, it slows down and the two continue together. Cars traveling together form a fleet, and a single car alone also counts as a fleet. If a car catches another exactly at the destination, they arrive as one fleet. Return the number of fleets that arrive.
| Destination | Positions | Speeds | Fleets | What happens |
|---|---|---|---|---|
| 20 | 14, 8, 2 | 3, 2, 6 | 2 | The car at 2 catches the slow car at 8; the car at 14 stays ahead alone |
| 15 | 1, 5, 9 | 2, 2, 2 | 3 | Same speed, so nobody catches anybody |
| 30 | 25, 10 | 1, 4 | 1 | Both need exactly 5 time units, so they meet at the line |
| 18 | 12, 8, 0 | 2, 5, 1 | 2 | The car at 8 catches the one at 12; the car at 0 is too slow to reach them |
Clarify that positions are distinct, that speeds are positive, and whether a car can start at the destination. A car already at the finish has a travel time of zero and still counts as its own fleet, which is an easy case to break.
What the question is really testing
Car Fleet looks like a physics simulation, and candidates who start simulating time steps get lost. The interviewer wants you to see that you never need the meeting point, only the order of the cars and their solo arrival times. That reduction, plus a clean argument for why a car behind can never break up a fleet ahead of it, is the whole problem.
The key observation
Look at the cars from the front. The car closest to the destination is never blocked, so it arrives at its solo time. The next car back is blocked only by the cars in front of it, and it arrives at the larger of its own solo time and the arrival time of the group directly ahead. If its solo time is smaller or equal, it catches up at or before the line and merges. If its solo time is larger, it can never catch up, so it leads a new fleet. Cars behind it then compare against this new, slower fleet.
Quadratic version: check everyone ahead
Without sorting, a car leads its own fleet exactly when every car ahead of it arrives strictly sooner on its own. Check that for each car by looking at all the others. That is O(n²). The reference below compares times without dividing: (target - p_j) / s_j >= (target - p_i) / s_i is the same test as (target - p_j) × s_i >= (target - p_i) × s_j when speeds are positive.
def count_groups_slow(target, position, speed):
n = len(position)
groups = 0
for i in range(n):
# car i leads a group if every car ahead of it arrives strictly sooner
leads = True
for j in range(n):
if position[j] > position[i]:
# time_j >= time_i, compared without division
if (target - position[j]) * speed[i] >= (target - position[i]) * speed[j]:
leads = False
break
if leads:
groups += 1
return groupsSort and sweep
Sort the cars by position, closest to the destination first. Walk through them while remembering the arrival time of the fleet just ahead. For each car, compute its solo time. If it is strictly larger, this car starts a new fleet and its time becomes the one to beat. Otherwise it merges and nothing changes. The count of new fleets is the answer.
def count_groups(target, position, speed):
cars = sorted(zip(position, speed), reverse=True) # closest to target first
groups = 0
slowest_ahead = -1.0 # arrival time of the group in front; none yet
for pos, spd in cars:
arrival = (target - pos) / spd
if arrival > slowest_ahead:
groups += 1
slowest_ahead = arrival
return groupsStarting the comparison value at -1 rather than 0 matters for one input: a car that begins at the destination has a solo time of 0, and with a starting value of 0 it would never be counted.
function countGroups(target, position, speed) {
const cars = position.map((p, i) => [p, speed[i]]);
cars.sort((a, b) => b[0] - a[0]); // closest to target first
let groups = 0;
let leadDist = -1; // distance and speed of the group in front, kept
let leadSpeed = 1; // apart so times compare without division; -1 = none yet
for (const [p, s] of cars) {
const dist = target - p;
if (dist * leadSpeed > leadDist * s) { // strictly later than the group ahead
groups++;
leadDist = dist;
leadSpeed = s;
}
}
return groups;
}Floating point or exact arithmetic?
Ties decide whether two cars merge, so it is fair to ask whether division can blur them. When positions and speeds are modest integers, two solo times that are equal as fractions also come out as the same floating-point number, because division is correctly rounded, so the Python version is fine for typical inputs. With very large values, distinct times could in principle round together. The JavaScript version avoids the question by keeping each time as a distance and a speed and comparing dist × leadSpeed with leadDist × speed. Mentioning this shows you thought about the tie rule.
About the stack version
Many write-ups push each car's time onto a stack and pop when a car behind merges. Since only the top of that stack is ever compared, the stack's size at the end equals the fleet count, and a single variable does the same job. Either is acceptable. If you use the stack, be ready to say that it is monotonic: times on it strictly increase from the front car to the back.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Simulate in small time steps | Depends on the step size, and can miss exact meetings | O(n) |
| Check every car ahead | O(n²) | O(1) |
| Sort, then sweep | O(n log n) | O(n) for the sorted pairs |
| Bucket by position, if positions are small integers | O(n + destination) | O(destination) |
Edge cases
- No cars: zero fleets.
- One car: one fleet, even if it starts at the destination.
- Equal solo times: the car behind merges, as in the 30-mile example.
- All cars with the same speed: no one catches anyone, so the answer is the number of cars.
- A slow car in front with fast cars behind: everything merges into one fleet.
Common mistakes
- Sorting by position ascending and sweeping from the back car forward, which compares each car with the wrong neighbor.
- Using greater-than-or-equal for a new fleet, which splits cars that meet exactly at the line.
- Computing a time-to-meet between every pair of cars. It is not needed and invites division by zero when speeds are equal.
- Integer division for the solo time in languages where
/between integers truncates.
Follow-ups
- When does each car join its fleet? Now you do need the meeting time: solve for when the two positions are equal, and check it happens before the destination.
- Cars can change lanes. The problem stops being a sweep; it becomes an event simulation.
- Report each fleet's size. Count how many cars merge into each leader during the sweep.
- Cars added over time. Keep cars in a sorted structure and recompute only the part behind the new car.
Saying it out loud
Fictional example
- Candidate
- Nobody can pass, so a car's arrival time is the max of its own solo time and the time of the group ahead. I don't need to know where they meet.
- Candidate
- I'll sort from the front of the road to the back and keep the slowest arrival time ahead. A car with a strictly larger solo time can't catch up, so it starts a new fleet.
- Candidate
- Equal times merge at the line, so the comparison is strict. Sorting dominates, so it's n log n. I'll compare by cross-multiplying to keep ties exact.
Continue with
Daily Temperatures uses a monotonic stack in the same spirit, and Largest Rectangle in Histogram pushes that idea further. Merge Intervals is another sort-then-sweep problem, and Generate Parentheses rounds out this group. Everything is listed on the coding problems hub.
Rehearse with Natively
Natively works on Mac and Windows. In a practice run it can read the Car Fleet prompt from a screenshot, explain why the meeting point never matters, and remind you to decide how ties at the line behave. Your mock is transcribed too, so you can reread how you justified sorting by position. The coding interview assistant page explains the coding features.
Questions people ask
How do you solve Car Fleet?
Sort cars by position from closest to the destination to farthest, and compute each car's solo travel time. Sweep in that order, keeping the slowest arrival time ahead; a car with a strictly larger time starts a new fleet. Count the new fleets.
Why is Car Fleet considered a stack problem?
Many solutions push each fleet's arrival time onto a stack and pop when a car merges, which makes the stack monotonic. Only the top is ever compared, so a single running variable gives the same answer.
Do two cars that meet exactly at the destination form one fleet?
In the usual version, yes. That is why the test for a new fleet uses strictly greater than, not greater than or equal.
What is the time complexity of Car Fleet?
O(n log n) because of the sort. The sweep after it is O(n). If positions are small integers, bucketing by position can replace the sort.
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.
