BackendML

Car Fleet

Medium2 min read
The Car Fleet problem requires determining how many groups of cars, called fleets, will arrive at a destination together when cars travel at the same speed or are slowed down by cars ahead of them.

Problem

There are n cars traveling toward the same destination. Each car has a starting position and a constant speed. A car cannot pass another car ahead of it.

Given the target position, an array position representing the starting positions of the cars, and an array speed representing their speeds, return the number of car fleets that will arrive at the destination.

A car fleet is a group of cars that travel together and arrive at the destination at the same time.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
target = 12
position = [10,8,0,5,3]
speed = [2,4,1,1,3]
Output
3

Example 2

Input
target = 10
position = [3]
speed = [3]
Output
1

Solution

This solution uses Sorting and a Monotonic Stack. First, we sort the cars by their starting positions in descending order so that we process the cars from the closest to the target to the farthest.

For each car, we calculate its time to reach the target using (target - position) / speed. If a car behind takes more time than the fleet ahead of it, it cannot catch that fleet, so it forms a new fleet. Otherwise, it catches the fleet ahead and becomes part of the same fleet.
class Solution {
    public int carFleet(int target, int[] position, int[] speed) {
        int n = position.length;
        int[][] cars = new int[n][2];

        for (int i = 0; i < n; i++) {
            cars[i][0] = position[i];
            cars[i][1] = speed[i];
        }
        Arrays.sort(cars, (a, b) -> b[0] - a[0]);
        Stack<Double> stack = new Stack<>();

        for (int[] car : cars) {
            double time = (double) (target - car[0]) / car[1];

            if (stack.isEmpty() || time > stack.peek()) {
                stack.push(time);
            }
        }
        return stack.size();
    }
}

Complexity

Sorting the cars takes O(n log n) time, and processing all cars takes O(n) time. Therefore, the overall time complexity is O(n log n).

The sorted array and stack require O(n) extra space.

Comments

No comments yet. Ask a question or share what helped.