Car Fleet

Count the groups of cars that reach the end of a one-lane road together, by comparing each car's arrival time with the group ahead.

A number of cars, n in all, drive toward the same destination, target miles down a one-lane road. Car i starts at mile position[i], before the destination, and drives at speed[i] miles per hour. No two cars start at the same position. A car can never pass the car in front of it. When it catches up, it slows down and the two drive on together as one group, called a fleet. A car that catches up exactly at the destination still joins that fleet. Return how many fleets arrive at the destination.

Example 1
Input: target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]
Output: 3
Explanation: the cars at 10 and 8 meet at 12; the car at 0 is alone; the cars at 5 and 3 meet at 6.
Example 2
Input: target = 10, position = [3], speed = [3]
Output: 1
Solution

The Idea

Think of a narrow country road where overtaking is impossible. A fast car that comes up behind a slow one has no choice but to stay behind it, so from then on the two travel at the slow car's speed and arrive together. The question is how many such groups reach the end of the road.

Example 1 has five cars heading for mile 12. Look at the picture below. Each box is a car with its speed, and under the road you see where it starts and how many hours it would need to reach the target if the road were empty. The car at 10, for example, has 2 miles left at speed 2, so it needs 1 hour.

Five cars on a one-lane road to mile 12. The cars at 10 and 8 need 1 hour each and form fleet 1. The car at 5 needs 7 hours; the car at 3 would need 3 hours but catches it at mile 6, forming fleet 2. The car at 0 needs 12 hours and arrives alone as fleet 3.

Start with the car in front, at 10. Nothing blocks it, and it arrives after 1 hour. The car at 8 is twice as fast and also needs 1 hour, so it reaches the car at 10 exactly at mile 12. They arrive together: fleet 1 in the picture.

The car at 5 needs 7 hours, far more than fleet 1, so it never gets close and starts fleet 2. The car at 3 is the interesting one. On an empty road it would need only 3 hours, but the slow car at 5 is in its way. It catches that car at mile 6 after one hour, then crawls behind it and arrives at 7 hours, as part of fleet 2. Last, the car at 0 needs 12 hours, more than the 7 of fleet 2, so it arrives alone as fleet 3.

Did we need to know that the car at 3 caught up at mile 6? Not really. Its 3 hours are less than the 7 hours of the fleet in front, so on its own it would arrive first. Passing is not allowed, so it must have caught up somewhere on the way.

That is the key insight: a car joins the fleet just ahead of it exactly when its own time to the target is not larger than that fleet's time. Going from the front car backward, each car only has to be compared with the one fleet directly in front of it.

Solution Approach

Turning that idea into code means settling three things: the order in which to visit the cars, what to remember about the fleets already formed, and how to compute the times without losing fractions. A last, optional part shows the same count with a stack.

Visiting the cars from the front

Why not simply play the drive out, moving every car a little at a time? Cars can meet at any moment, not only on whole hours, so the steps would have to be tiny, and two cars could still meet between two steps unnoticed. Comparing times avoids all of that.

A car's fate depends only on the cars in front of it, never on those behind, so the cars are visited from the one closest to the target to the one farthest away. The input is not in that order, and position[i] and speed[i] belong to the same car. So instead of sorting the positions, we sort the car numbers 0 to n - 1 by their position, largest first. Each number still finds its own speed.

What to remember about the fleets ahead

Which fleet can the next car catch? Only the one directly in front of it, because that fleet is the slowest so far: every fleet further ahead arrives sooner. So one number is enough, the arrival time of the fleet just ahead, kept in a variable named slowest.

When a car's time is larger than slowest, it starts a new fleet, and its time becomes the new slowest. Otherwise it joins, and the fleet still arrives at its old time, since the joining car has to follow it. Equal times count as joining: the two cars meet right at the target, as the cars at 10 and 8 do.

Keeping the fractions in the times

Times are rarely whole numbers. A car 10 miles away at speed 3 needs 3.33 hours, and a car 9 miles away at speed 3 needs exactly 3. In Java, dividing one int by another throws away the fraction, so both would come out as 3, and the car farther back would look as if it caught the one ahead. Casting to double before dividing keeps 3.33.

The stack version (optional)

Many solutions keep the fleets on a stack: a pile where items are only added to and taken from the top. The cars are visited from the front as before. A car whose time is larger than the time on top of the stack is pushed, that is, added on top as a new fleet. At the end, the size of the stack is the answer. Only the top is ever looked at, so slowest can stand in for the top and a counter for the size, which is what the code below does.

Java Solution

The method carFleet works in these steps:

  1. First, fill an array order with the car numbers 0 to n - 1. It is an Integer[] rather than an int[], because only arrays of objects can be sorted with a comparator in Java.
  2. Sort order with Arrays.sort and a comparator that compares position[b] with position[a], so the car closest to the target comes first.
  3. Set the counter fleets to 0 and slowest to 0. No fleet is ahead yet, and every car starts before the target, so its time is above 0 and the first car always starts a fleet.
  4. Loop over order. For each car i, compute time, its hours to the target, as (double) (target - position[i]) / speed[i].
  5. If time is larger than slowest, the car cannot catch the fleet ahead: add 1 to fleets and set slowest to time. Otherwise the car joins that fleet and nothing changes.
  6. After the loop, fleets is the answer.

The main method runs both examples, two cars that meet exactly at the target, three equally fast cars, a fast car stuck behind a slow one, and the two cars whose times differ only by a fraction.

Java
import java.util.Arrays;

public class CarFleet {

    public static int carFleet(int target, int[] position, int[] speed) {
        int n = position.length;
        Integer[] order = new Integer[n];
        for (int i = 0; i < n; i++) {
            order[i] = i;
        }
        Arrays.sort(order, (a, b) -> Integer.compare(position[b], position[a])); // front first
        int fleets = 0;
        double slowest = 0;                       // arrival time of the fleet just ahead
        for (int i : order) {
            double time = (double) (target - position[i]) / speed[i];
            if (time > slowest) {                 // cannot catch the fleet ahead: a new fleet
                fleets++;
                slowest = time;
            }
        }
        return fleets;
    }

    public static void main(String[] args) {
        System.out.println(carFleet(12, new int[] {10, 8, 0, 5, 3}, new int[] {2, 4, 1, 1, 3}));
        System.out.println(carFleet(10, new int[] {3}, new int[] {3}));
        System.out.println(carFleet(10, new int[] {6, 8}, new int[] {2, 1}));
        System.out.println(carFleet(10, new int[] {8, 5, 0}, new int[] {1, 1, 1}));
        System.out.println(carFleet(10, new int[] {0, 4, 2}, new int[] {2, 1, 3}));
        System.out.println(carFleet(10, new int[] {0, 1}, new int[] {3, 3}));
    }
}

Running it prints:

Output
3
1
1
3
1
2

The 3 and the 1 at the top match the two examples. The third line, 1, comes from cars at 6 and 8 with speeds 2 and 1. Both need exactly 2 hours, so the car at 6 meets the other one at the target, and the strict time > slowest check keeps them as one fleet.

The fourth line shows three cars at the same speed 1: their times are 2, 5 and 10 hours, each larger than the one before, so nobody catches anybody and the answer is 3. In the fifth line, the car at 4 crawls at speed 1 and needs 6 hours. The car at 2 needs only 2.67 hours and the car at 0 needs 5, so all three arrive as a single fleet.

The last line, 2, is the fraction case from above: cars at 0 and 1, both at speed 3, need 3.33 and 3 hours. A version of the loop that divides two int values gets 3 for both cars and returns 1 for this input. The double times keep them apart.

The original implementation, CarFleet.java, is on GitHub.

Complexity

The work is one sort of the car numbers and then one pass over them.

  • Time: O(n log n), because sorting the n car numbers by position dominates. Filling order and the loop that compares each car with slowest each visit every car once, which is O(n).
  • Space: O(n), for the order array of n boxed car numbers, plus the temporary storage that Arrays.sort uses when it sorts objects. The loop itself keeps only fleets, slowest and time.

Sorting first and then comparing each item only with the group just before it also solves Merge Intervals.