KatInterview

883. Car Fleet

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of the problem is to determine how many distinct groups of cars, or "fleets," will arrive at a target destination. A fleet is formed when a faster car catches up to a slower car. Once they meet, they travel together at the speed of the slower car. The key is that a car cannot pass another. This implies that a car's arrival time is limited by any car that starts ahead of it. If a car would, by itself, arrive earlier than a car in front of it, it will instead be forced to slow down and arrive at the same time, thus joining the front car's fleet.

Solution

Car Fleet in Python

class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        n = len(position)
        if n == 0:
            return 0

        # Combine position and speed, then sort by position.
        # Sorting in ascending order of position.
        cars = sorted(zip(position, speed))

        fleets = 0
        leader_arrival_time = 0.0

        # Iterate from the car closest to the target to the farthest.
        # This corresponds to iterating backwards through the sorted list.
        for i in range(n - 1, -1, -1):
            pos, spd = cars[i]
            
            # Calculate the time for the current car to reach the target.
            current_arrival_time = (target - pos) / spd

            # If the current car's arrival time is greater than the leader's arrival time,
            # it means this car cannot catch up to the fleet in front.
            # Thus, it forms a new fleet.
            if current_arrival_time > leader_arrival_time:
                fleets += 1
                # This car now becomes the leader of the new fleet.
                leader_arrival_time = current_arrival_time
            # Otherwise, it catches up and joins the fleet ahead. No new fleet is formed.

        return fleets

Car Fleet in Java

class Solution {
    public int carFleet(int target, int[] position, int[] speed) {
        int n = position.length;
        if (n == 0) {
            return 0;
        }

        // Create a 2D array to store position and speed for each car.
        int[][] cars = new int[n][2];
        for (int i = 0; i < n; i++) {
            cars[i][0] = position[i];
            cars[i][1] = speed[i];
        }

        // Sort cars based on their starting position in ascending order.
        java.util.Arrays.sort(cars, (a, b) -> Integer.compare(a[0], b[0]));

        int fleets = 0;
        double leaderArrivalTime = 0.0;

        // Iterate from the car closest to the target to the farthest.
        for (int i = n - 1; i >= 0; i--) {
            // Calculate the time for the current car to reach the target.
            // Use double for precision.
            double currentArrivalTime = (double)(target - cars[i][0]) / cars[i][1];

            // If the current car's arrival time is greater than the leader's arrival time,
            // it means this car cannot catch up to the fleet in front.
            // Thus, it forms a new fleet.
            if (currentArrivalTime > leaderArrivalTime) {
                fleets++;
                // This car now becomes the leader of the new fleet.
                leaderArrivalTime = currentArrivalTime;
            }
            // Otherwise, it catches up and joins the fleet ahead. No new fleet is formed.
        }

        return fleets;
    }
}

Car Fleet in C++

class Solution {
public:
    int carFleet(int target, vector<int>& position, vector<int>& speed) {
        int n = position.size();
        if (n == 0) {
            return 0;
        }

        // Create a vector of pairs to store position and speed together.
        vector<pair<int, int>> cars(n);
        for (int i = 0; i < n; ++i) {
            cars[i] = {position[i], speed[i]};
        }

        // Sort cars based on their starting position in ascending order.
        sort(cars.begin(), cars.end());

        int fleets = 0;
        double leader_arrival_time = 0.0;

        // Iterate from the car closest to the target to the farthest.
        for (int i = n - 1; i >= 0; --i) {
            // Calculate the time for the current car to reach the target.
            // Use double for precision.
            double current_arrival_time = (double)(target - cars[i].first) / cars[i].second;
            
            // If the current car's arrival time is greater than the leader's arrival time,
            // it means this car cannot catch up to the fleet in front.
            // Thus, it forms a new fleet.
            if (current_arrival_time > leader_arrival_time) {
                fleets++;
                // This car now becomes the leader of the new fleet.
                leader_arrival_time = current_arrival_time;
            }
            // Otherwise, it catches up and joins the fleet ahead. No new fleet is formed.
        }

        return fleets;
    }
};

Car Fleet in TypeScript

function carFleet(target: number, position: number[], speed: number[]): number {
    const n = position.length;
    if (n === 0) {
        return 0;
    }

    // Create an array of car objects to store position and speed together.
    const cars = position.map((pos, i) => ({
        position: pos,
        speed: speed[i]
    }));

    // Sort cars based on their starting position in ascending order.
    cars.sort((a, b) => a.position - b.position);

    let fleets = 0;
    let leaderArrivalTime = 0.0;

    // Iterate from the car closest to the target to the farthest.
    for (let i = n - 1; i >= 0; i--) {
        // Calculate the time for the current car to reach the target.
        const currentArrivalTime = (target - cars[i].position) / cars[i].speed;

        // If the current car's arrival time is greater than the leader's arrival time,
        // it means this car cannot catch up to the fleet in front.
        // Thus, it forms a new fleet.
        if (currentArrivalTime > leaderArrivalTime) {
            fleets++;
            // This car now becomes the leader of the new fleet.
            leaderArrivalTime = currentArrivalTime;
        }
        // Otherwise, it catches up and joins the fleet ahead. No new fleet is formed.
    }

    return fleets;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.