↻one more pass.
Stack · Medium

Car Fleet: the idea to remember.

Cars drive toward one target without passing; count the fleets that arrive. Positions are distinct.

Solve on LeetCode ↗

The core insight

Read cars from nearest to farthest from the target and keep the slowest arrival time ahead.

Why it works

A trailing car with an arrival time no greater than the fleet ahead must catch it before or at the target.

The mistake to avoid

Use floating point division; catching exactly at the target still creates one fleet.

Time: O(n log n)Space: O(n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Read cars from nearest to farthest from the target and keep the slowest arrival time ahead.
public int carFleet(int target, int[] position, int[] speed) {
    if (position.length == 1) return 1;
    Stack<Double> stack = new Stack<>();
    int[][] combine = new int[position.length][2];
    for (int i = 0; i < position.length; i++) {
        combine[i][0] = position[i];
        combine[i][1] = speed[i];
    }

    Arrays.sort(combine, java.util.Comparator.comparingInt(o -> o[0]));
    for (int i = combine.length - 1; i >= 0; i--) {
        double currentTime = (double) (target - combine[i][0]) /
        combine[i][1];
        if (!stack.isEmpty() && currentTime <= stack.peek()) {
            continue;
        } else {
            stack.push(currentTime);
        }
    }
    return stack.size();
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.