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, targetposition[i]speed[i]
Example 1
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
Output: 1
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.
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]speed[i]
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 slowestslowest
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 intdouble
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
Java Solution
The method carFleet
- First, fill an array
with the car numbers 0 to n - 1. It is anorder rather than anInteger[] , because only arrays of objects can be sorted with a comparator in Java.int[] - Sort
withorder and a comparator that comparesArrays.sort withposition[b] , so the car closest to the target comes first.position[a] - Set the counter
to 0 andfleets 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.slowest - Loop over
. For each car i, computeorder , its hours to the target, astime .(double) (target - position[i]) / speed[i] - If
is larger thantime , the car cannot catch the fleet ahead: add 1 toslowest and setfleets toslowest . Otherwise the car joins that fleet and nothing changes.time - After the loop,
is the answer.fleets
The main
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:
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
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 intdouble
The original implementation,
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
and the loop that compares each car withorder each visit every car once, which is O(n).slowest - Space: O(n), for the
array of n boxed car numbers, plus the temporary storage thatorder uses when it sorts objects. The loop itself keeps onlyArrays.sort ,fleets andslowest .time
Sorting first and then comparing each item only with the group just before it also solves