15% off all plans & roadmaps Use code

See plans

Car Fleet

Updated

TL;DR: Count how many groups of cars reach the target together when no car can pass another. Sort by position, compute each arrival time, and count every car that arrives strictly later than all fleets ahead of it.

Problem

There is a road with a destination at mile target. You are given two integer arrays, position and speed, of the same length. Car i starts at position[i] and drives toward target at the constant speed speed[i].

Cars cannot pass each other. If a faster car comes up behind a slower car, it slows down to the slower car's speed and they travel together. A fleet is a group of one or more cars that arrive at target at the same time. A car that never catches anyone is a fleet on its own.

Return the number of fleets that arrive at target.

Example 1

Input: target = 20, position = [3,8,14,17], speed = [5,3,2,1]
Output: 2
Explanation: The cars at 17 and 14 reach the target at the same time, so they form one fleet. The car at 8 is a second fleet, and the car at 3 catches it before the target. That gives two fleets.

Example 2

Input: target = 30, position = [4,10,18,25], speed = [6,4,3,2]
Output: 3
Explanation: The car at 25 arrives after 2.5 time units and the car at 18 after 4, so they stay separate. The car at 10 would arrive after 5, and the car at 4 catches it on the way. That gives three fleets.

Example 3

Input: target = 25, position = [2,7,16,21], speed = [2,5,2,4]
Output: 3
Explanation: The car at 21 is the first fleet. The car at 7 catches the car at 16 and they form the second fleet. The car at 2 is too slow to catch that fleet and stays alone.

Constraints

  • 1 <= target <= 10^6
  • 1 <= position.length == speed.length <= 10^5
  • 0 <= position[i] < target
  • 1 <= speed[i] <= 10^6
  • All values in position are distinct.
  • Every position[i] and speed[i] is an integer, and both describe the same car.

Constraints that matter

  • n up to 10^5 rules out comparing every car with every other car in the worst case, which is about 10^10 operations. You need roughly O(n log n).
  • Positions are distinct, so after sorting there is a strict order from the car nearest the target to the farthest. No tie-breaking by speed is needed.
  • All values are integers, so each arrival time is a fraction (target - position) / speed. Cross-multiplying compares two times exactly with no floating-point error.
  • The products reach about 10^6 * 10^6 = 10^12, which overflows a 32-bit int. Java, C++ and C# need 64-bit integers for the comparison.
  • position[i] < target means every car has a positive distance to travel, so every arrival time is greater than zero.

View on LeetCode

Hints

Hint 1

Cars cannot pass, so a car's real arrival time depends only on the cars ahead of it.

Hint 2

For every car, ask whether it leads its own fleet.

Solution

Intuition

Cars cannot pass, so a car's real arrival time depends only on the cars ahead of it. If you ignore blocking, car i needs (target - position[i]) / speed[i] time units. Call that its solo time. A car with a smaller solo time than a car ahead of it will catch that car, and from then on it travels at the slower pace.

Picture a single-file line of runners finishing a race, read from the front. The stack top is the finish time of the latest group, and a runner who finishes no later than that group joins it and adds nothing to the count.

That suggests looking at cars in order from the one nearest the target to the one farthest away. For each car, the only question is whether it arrives strictly later than every fleet already formed ahead of it. If yes, it never catches anyone and starts a new fleet. If its solo time is less than or equal to the fleet ahead, it merges into that fleet.

This is a sort plus a monotonic stack. After sorting by position, you keep a stack of fleet arrival times. A new time is pushed only when it is strictly larger than the top, so the stack is strictly increasing from bottom to top. Nothing is ever popped, because a merged car adds no entry. The final stack size is the answer.

Comparing with the top is enough because the top is the largest time so far. A car slower than the top fleet cannot be caught by that fleet's cars, and no fleet further ahead arrives later than the top. A car faster than the top fleet merges into it and takes the top's time.

Try Example 1 with target 20. Sorted from the front, the cars at 17, 14, 8, 3 have solo times 3, 3, 4 and 3.4. The stack gets 3, skips 3 (equal means same fleet), pushes 4, and skips 3.4 because it is below 4. The stack holds two entries, so the answer is 2.

Watch the pattern animation

Worked example

Input: target = 1, position = [0], speed = [1]
Output: 1
Explanation: There is one car, so there is one fleet. It needs (1 - 0) / 1 = 1 time unit to arrive, and no car sits ahead of it that could block it.

Approach 1: Brute force

For every car, ask whether it leads its own fleet. A car leads a fleet when no car ahead of it has a solo time greater than or equal to its own. If such a car exists, this car is caught by that car's fleet or reaches the target with it, so it adds no new fleet.

Scan every other car, keep only those with a larger position, and compare solo times. Count the cars for which no such blocker exists. Each fleet is counted exactly once, by its frontmost car. Compare times as fractions with cross-multiplication so the answer is exact.

Steps

  1. Set fleets = 0.
  2. For each car i, compute its distance d_i = target - position[i].
  3. Loop over every car j and skip it unless position[j] > position[i].
  4. For each car j ahead, compute d_j = target - position[j] and check d_j * speed[i] >= d_i * speed[j]. This says time_j >= time_i without division.
  5. If any such j exists, car i is absorbed. Stop checking and move to the next car.
  6. If no j blocks car i, increment fleets.
  7. Return fleets.

Dry run

Example: target = 1, position = [0], speed = [1].

  • Car 0 has distance 1 - 0 = 1.
  • The inner loop looks at car 0 itself, but position[0] > position[0] is false, so nothing is compared.
  • No car ahead blocks it, so fleets becomes 1.

The result is 1, which matches the expected output.

A larger check uses target 20, position [3,8,14,17], speed [5,3,2,1]. The solo times are 3.4, 4, 3, 3 for the cars at 3, 8, 14, 17. The car at 17 has no car ahead, so it counts. The car at 14 sees 17 with time 3 >= 3, so it is absorbed.

The car at 8 sees times 3 and 3, both below 4, so it counts. The car at 3 sees the car at 8 with time 4 >= 3.4, so it is absorbed. The total is 2.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the number of cars. The outer loop runs n times and the inner loop can scan up to n other cars, so the worst case is about n * n comparisons. That happens when no car is ever blocked, which makes the early break useless, and at n = 10^5 it means about 10^10 comparisons, which is too slow. Only a few integers are stored, so extra space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        n = len(position)
        fleets = 0
        for i in range(n):
            di = target - position[i]
            blocked = False
            for j in range(n):
                if position[j] > position[i]:
                    dj = target - position[j]
                    # time_j >= time_i  <=>  dj / speed[j] >= di / speed[i]
                    if dj * speed[i] >= di * speed[j]:
                        blocked = True
                        break
            if not blocked:
                fleets += 1
        return fleets
Monotonic Stack pattern infographic for Car Fleet

Solution pattern

Monotonic Stack

Part of Stack Patterns

Approach 2: Sort, then monotonic stack of arrival timesOptimalMonotonic Stack

What's slow: the brute force re-checks every car ahead for every car, even though most of that information is redundant. If you already know the fleets ahead, the only thing that matters is the latest arrival time among them.

The insight that fixes it: sort the cars by position, nearest to the target first, and keep a stack of fleet arrival times. For each car compute its solo time. If it is strictly greater than the top of the stack, no fleet ahead can absorb it, so push it as a new fleet. Otherwise it catches the top fleet and you push nothing.

The stack is strictly increasing, so the top is always the maximum and one comparison per car is enough. The answer is the stack size.

To avoid floating-point error, store each time as a numerator and denominator, (target - position, speed). Compare a/b > c/d as a * d > c * b. Both sides stay under 10^12 and fit in a 64-bit integer.

Steps

  1. Pair each position with its speed.
  2. Sort the pairs by position in descending order, so the car nearest the target comes first.
  3. Create an empty stack of (numerator, denominator) pairs, where numerator is target - position and denominator is speed.
  4. For each car, compute num = target - position and den = speed.
  5. If the stack is empty, or num * topDen > topNum * den, push (num, den).
  6. Otherwise the car merges into the fleet at the top, so push nothing.
  7. Return the stack size.

Dry run

Page example: target = 1, position = [0], speed = [1].

StepCar (pos, speed)Solo timeCompare with topActionStack size
1(0, 1)1/1stack emptypush (1, 1)1

The stack holds one entry, so the answer is 1.

A longer trace on target = 20, position = [3,8,14,17], speed = [5,3,2,1]. After sorting by position descending the cars are (17,1), (14,2), (8,3), (3,5).

StepCarSolo timeTop timeActionStack (times)
1(17, 1)3/1 = 3nonepush[3]
2(14, 2)6/2 = 333 > 3 is false, merge[3]
3(8, 3)12/3 = 434 > 3, push[3, 4]
4(3, 5)17/5 = 3.443.4 > 4 is false, merge[3, 4]

The final stack size is 2, which matches Example 1.

Complexity

TimeO(n log n)
SpaceO(n)

Let n be the number of cars. Sorting costs O(n log n). The scan visits each car once with one constant-time comparison and at most one push, so it is O(n), and the sort dominates at O(n log n) overall. The sorted pair list holds n entries and the stack holds at most n entries, so extra space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        # nearest to the target first
        cars = sorted(zip(position, speed), reverse=True)
        stack = []  # (numerator, denominator) of each fleet's arrival time
        for pos, sp in cars:
            num = target - pos
            # new fleet only if strictly later than the fleet ahead
            if not stack or num * stack[-1][1] > stack[-1][0] * sp:
                stack.append((num, sp))
        return len(stack)

Common mistakes

  • Sorting by position ascending. If you scan from the rear, the fleet ahead is not known yet and the comparison with the top is meaningless. Sort descending so the car nearest target goes first.
  • Using time >= top to push a new fleet, or < to merge. Equal arrival times mean the cars arrive together, which is one fleet. Push only on a strictly greater time and merge on <=.
  • Computing (target - position) / speed with integer division, as in (target - pos) // sp or / on ints in Java and C++. Times like 2.5 and 2 become equal and fleets merge wrongly. Use cross-multiplication or a floating-point division.
  • Multiplying two ints in Java, C++ or C# without widening, as in num * den with int types. The product can reach 10^12 and overflow. Declare the numerator and denominator as long or long long before multiplying.
  • Sorting only the position array and leaving speed untouched. The two arrays describe the same cars, so the pairs must move together. Sort pairs or sort indices.
  • Comparing each car with every earlier fleet instead of only the top of the stack. It still works but brings back O(n^2) work. The stack is increasing, so the top is the maximum and one comparison is enough.

Edge cases

  • One car, such as target = 1, position = [0], speed = [1]: the answer is 1.
  • All cars at distinct positions but with the same solo time, for instance times all equal to 5: they form one fleet, so the answer is 1.
  • Speeds so that the rear car is much faster than everyone ahead: every car merges into the front fleet and the answer is 1.
  • Speeds so that cars farther back are always slower and arrive later: no one catches anyone, so the answer equals n.
  • Input positions given in unsorted order, like [17, 3, 14, 8]: the sort must carry each speed with its position.
  • Maximum values target = 10^6, position = 0, speed = 1 alongside speed = 10^6: cross-multiplied products reach 10^12, so 32-bit arithmetic overflows.

Follow-ups interviewers ask

Can you avoid floating point entirely?
Yes. Store each arrival time as the pair (target - position, speed) and compare a/b > c/d as a * d > c * b. The products are at most 10^6 * 10^6 = 10^12, which fits in a 64-bit integer and in a JavaScript double. That makes every comparison exact.
Do you actually need a stack, or does a single variable do?
A single variable is enough. Only the top of the stack is ever read, and nothing is ever popped, so keep the latest fleet's arrival time and a counter. When a car's time is strictly greater than that variable, increment the counter and replace the variable. The sort still costs O(n log n) and O(n) space.
Can you beat O(n log n)?
Positions are integers below target, so you can bucket-sort by position when target is small. Allocate an array of size target, place each car at its position, and scan from target - 1 down to 0. That costs O(n + target) time and O(target) space. With target up to 10^6 and n up to 10^5 this helps only in some cases, so the comparison sort is the general answer.

Car Fleet FAQ

What is the time complexity of Car Fleet?

O(n log n), where n is the number of cars. Sorting by position costs O(n log n) and the single pass over the sorted cars is O(n). Space is O(n) for the sorted pairs and the stack.

Why use a monotonic stack for Car Fleet?

After sorting from the target backward, the fleet arrival times you keep are strictly increasing, which is the monotonic stack invariant. Each new car only needs to be compared with the top, the latest fleet. If it is strictly later, it is pushed as a new fleet. Otherwise it merges and nothing changes.

Why does the car fleet solution sort by position descending?

A car's final time depends only on the cars ahead of it. Processing from the one nearest the target means every fleet in front has been decided before the next car is considered. Scanning the other way would require knowing fleets you have not built yet.

Should Car Fleet use floating-point division or integer cross-multiplication?

Either works within these limits, but integer cross-multiplication is exact and avoids rounding questions when two times are equal. Never use integer division: (target - pos) // speed truncates 2.5 to 2 and breaks the comparison. If you use floats, divide with a floating type, such as / in Python or a cast to double in Java and C++.

Can Car Fleet be solved in O(1) extra space?

Not in the usual sense. You can replace the stack with one variable and a counter, but you still need the cars in sorted order. Sorting the pairs needs O(n) extra space, or you can sort in place in languages that allow it and pay for the pairing. A bucket by position uses O(target) space instead.

How is Car Fleet (LeetCode 853) different from a simulation?

A simulation moves every car in small time steps and merges them when they meet. That introduces time-step choices and rounding problems. The accepted solution never simulates motion. It computes each car's solo arrival time and uses the fact that cars cannot pass to decide merges by comparison alone.

Asked at

See which companies ask this — Pro

Practise it