Car Fleet

Medium Monotonic Stack Monotonic Stack

Car Fleet is a medium monotonic stack problem solved with the monotonic stack pattern. The best approach, optimal (index by position, scan from the front), runs in O(n + target) time and O(target) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (check every car ahead) up.

Problem

There are n cars on a one-lane road, all driving towards the same destination at mile target. Car i starts at mile position[i] and drives at a constant speed[i] miles per hour.

The road is too narrow to overtake. When a car catches up with a slower car (or group of cars) in front of it, it stays right behind it and from then on drives at that slower speed. Cars driving together like this form a car fleet; their length is ignored, so they count as being at the same position. A single car on its own is also a fleet.

If a car catches up with a fleet exactly at mile target, it still counts as part of that fleet.

Return the number of car fleets that arrive at the destination.

Examples

Example 1

Input
target = 10, position = [6,8,0,3], speed = [2,1,1,3]
Output
3
Why
The car at 8 needs 2 hours to reach 10, and so does the car at 6, which catches it exactly at the target: one fleet. The car at 3 needs 7/3 hours, more than 2, so it never catches them and forms a second fleet. The car at 0 needs 10 hours and forms a third.

Example 2

Input
target = 5, position = [2], speed = [3]
Output
1
Why
A single car is a fleet on its own.

Example 3

Input
target = 20, position = [0,4,8], speed = [6,3,1]
Output
1
Why
Alone, the car at 8 would need 12 hours, the car at 4 about 5.3 and the car at 0 about 3.3. Both faster cars catch up with the slow car at the front before the target, so all three arrive together as one fleet.

Constraints

  • n == position.length == speed.length
  • 1 <= n <= 10^5
  • 0 < target <= 10^6
  • 0 <= position[i] < target
  • All values of position are distinct.
  • 0 < speed[i] <= 10^6

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (check every car ahead)O(n^2)O(1)
Sort by position and keep a monotonic stackO(n log n)O(n)
Optimal (index by position, scan from the front)O(n + target)O(target)

1Brute force (check every car ahead)

TimeO(n^2)For each of the n cars, every other car is checked.
SpaceO(1)Only a few variables.

Give every car its solo time, the hours it would need to reach the target on an empty road. A car ends up behind some other car exactly when some car in front of it has a solo time at least as large as its own: it would reach that car, or the group that car is in, no later than the target. Cars that are never held up are the fronts of the fleets, so count the cars for which no car ahead is that slow.

  1. For each car i, compute time = (target - position[i]) / speed[i].
  2. Look at every car j with position[j] > position[i]. If its solo time is >= time, car i is blocked.
  3. If car i is not blocked, it leads its own fleet: add one.
  4. Return the count.
class Solution {
    public int carFleet(int target, int[] position, int[] speed) {
        int n = position.length, fleets = 0;
        for (int i = 0; i < n; i++) {
            double time = (double) (target - position[i]) / speed[i];
            boolean blocked = false;
            for (int j = 0; j < n; j++) {
                if (position[j] > position[i] && (double) (target - position[j]) / speed[j] >= time) {
                    blocked = true;
                    break;
                }
            }
            if (!blocked) fleets++;
        }
        return fleets;
    }
}

2Sort by position and keep a monotonic stack

TimeO(n log n)Sorting takes O(n log n). Each car is pushed once and popped at most once, so the stack work is O(n).
SpaceO(n)The sorted pairs and the stack each hold up to n entries.

Sort the cars by position, from the back of the road to the front, and keep a stack of the arrival times of the fleets formed so far (the fleets behind the current car). When a new car further ahead comes in with solo time t, every fleet behind it that would arrive no later than t catches it and merges into it, so pop those times. Then push t, the arrival time of the merged fleet, which is decided by the slower car in front. The stack's times always decrease from bottom to top, and its size at the end is the number of fleets.

  1. Pair each position with its speed and sort the pairs by position, smallest first.
  2. For each car: time = (target - position) / speed.
  3. While the stack is not empty and its top is <= time, pop: that fleet catches this car.
  4. Push time. Return the size of the stack.
class Solution {
    public int carFleet(int target, int[] position, int[] speed) {
        int n = position.length;
        int[][] cars = new int[n][];
        for (int i = 0; i < n; i++) cars[i] = new int[] { position[i], speed[i] };
        Arrays.sort(cars, (a, b) -> a[0] - b[0]);
        Deque<Double> stack = new ArrayDeque<>();
        for (int[] car : cars) {
            double time = (double) (target - car[0]) / car[1];
            while (!stack.isEmpty() && stack.peek() <= time) stack.pop();
            stack.push(time);
        }
        return stack.size();
    }
}

3Optimal (index by position, scan from the front)

TimeO(n + target)One pass over the cars to fill the slots and one pass over the target slots, with no sorting.
SpaceO(target)The array has one slot per position from 0 to target - 1.

Positions are distinct integers below target, so instead of sorting, write each car's solo time into a slot of an array indexed by position. Then walk the slots from the target backwards, remembering slowest, the arrival time of the fleet directly ahead. A car whose time is larger than slowest can never catch that fleet, so it starts a new fleet and becomes the new slowest. A car whose time is not larger catches up and simply joins, arriving at slowest. Empty slots hold 0 and never start a fleet, because every real time is positive.

  1. time[position[i]] = (target - position[i]) / speed[i] for every car; other slots stay 0.
  2. Set slowest = 0 and fleets = 0.
  3. For p from target - 1 down to 0: if time[p] > slowest, set slowest = time[p] and add one fleet.
  4. Return fleets.
class Solution {
    public int carFleet(int target, int[] position, int[] speed) {
        double[] time = new double[target];
        for (int i = 0; i < position.length; i++) {
            time[position[i]] = (double) (target - position[i]) / speed[i];
        }
        int fleets = 0;
        double slowest = 0;
        for (int p = target - 1; p >= 0; p--) {
            if (time[p] > slowest) {
                slowest = time[p];
                fleets++;
            }
        }
        return fleets;
    }
}

Edge cases to test

  • A single car: one fleet
  • Two cars that would arrive at exactly the same moment: they meet at the target and count as one fleet
  • Every car behind is slower than the one ahead: no one catches anyone, so there are n fleets
  • The front car is the slowest: everyone catches it, so there is one fleet
  • A car that catches a fleet slows down to the fleet's speed, so a fast car further back may then catch the whole group
  • Positions are not given in sorted order
  • Arrival times are fractions; compare them as doubles (or cross-multiply as longs), never with integer division

Hints

Hint 1

Cars never pass each other, so what happens to a car depends only on the cars in front of it. Look at the cars from the one closest to the target backwards.

Hint 2

Work out when each car would reach the target if the road were empty: (target - position) / speed. A car joins the group ahead of it exactly when it would arrive no later than that group.

Hint 3

Once a car is stuck behind a slower group, it arrives when that group arrives. So walking from the front, you only need the arrival time of the group directly ahead.

FAQ

What is the best time complexity for Car Fleet?

Optimal (index by position, scan from the front) runs in O(n + target) time and O(target) extra space. One pass over the cars to fill the slots and one pass over the target slots, with no sorting.

Which pattern does Car Fleet use?

It is a monotonic stack problem that uses the monotonic stack pattern. Other problems with the same pattern: Next Greater Element I, Daily Temperatures, Next Greater Element II.

Is there a brute force solution for Car Fleet?

Yes. Brute force (check every car ahead) takes O(n^2) time and O(1) space. Give every car its solo time, the hours it would need to reach the target on an empty road.

Which edge cases should I test for Car Fleet?

A single car: one fleet; Two cars that would arrive at exactly the same moment: they meet at the target and count as one fleet; Every car behind is slower than the one ahead: no one catches anyone, so there are n fleets; The front car is the slowest: everyone catches it, so there is one fleet; A car that catches a fleet slows down to the fleet's speed, so a fast car further back may then catch the whole group; Positions are not given in sorted order; Arrival times are fractions; compare them as doubles (or cross-multiply as longs), never with integer division.