Problem 853

Abstract / Summary

Several cars travel toward a destination and we must determine how many reach it without catching up to another car.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0853.py

class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        fleets = len(position)
        cars   = sorted(zip(position, speed), reverse = True)
        arrive = [ (target - p) / s for p, s in cars ] # time of arrival
        incoming = 0 # time of arrival of current fleet
        for a in arrive:
            if a <= incoming: # bump into one of the cars ahead
                fleets  -= 1
            else:
                incoming = a  # leader of a new fleet

        return fleets
13 lines | 547 bytes | submitted October 25, 2023 | GitHub   33% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (900k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Monotonic Stack
  • Sorting
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method carFleet that computes the number of car fleets that will arrive at a destination point target. A fleet is defined as a group of cars that travel together because a faster car catches up to a slower one ahead of it and then moves at the slower car’s speed. The algorithm processes the positions and speeds of the cars, determines the arrival times, and merges cars into fleets when appropriate.

Key Steps

The method begins by initializing a counter for the total number of fleets based on the number of cars supplied:

fleets = len(position)

Next, the positions and speeds are paired and sorted in descending order of position. Sorting in reverse order ensures that the cars are examined from the one closest to the target to the one farthest away:

cars = sorted(zip(position, speed), reverse=True)

For each car, the time required to reach the target is calculated. This is done by subtracting the car’s current position from the target distance and dividing by its speed:

arrive = [(target - p) / s for p, s in cars]

A variable incoming is used to keep track of the arrival time of the leading car of the current fleet. It is initially set to zero, indicating that no fleet has been established yet:

incoming = 0

The algorithm then iterates over the list of arrival times. For each arrival time a, it checks whether the car would catch up to the fleet ahead. If the current car’s arrival time is less than or equal to incoming, it means the car will merge with the fleet ahead, and the total fleet count is decremented. Otherwise, the car becomes the leader of a new fleet, and incoming is updated to its arrival time:

for a in arrive:
    if a <= incoming:
        fleets -= 1
    else:
        incoming = a

Finally, the method returns the computed number of fleets:

return fleets

Edge Cases Handled

When the input lists position and speed are empty, len(position) evaluates to zero, and the method correctly returns zero fleets without entering the loop.

If multiple cars share the same position, the sorting step places them together, and the subsequent arrival time calculation treats each car independently. Cars that have identical arrival times are considered part of the same fleet because the condition a <= incoming will be true for the later car, causing a fleet count reduction.

Cars with a speed of zero are not possible under the problem constraints; however, the division (target - p) / s would raise a runtime error if such a speed appeared. The code assumes valid positive speeds, which aligns with the intended usage.

When a car is already at the target (p == target), its arrival time becomes zero. Since incoming starts at zero, the first car at the target will be treated as a new fleet, and any subsequent car also at the target will merge into that fleet because its arrival time (zero) satisfies a <= incoming.

The algorithm also correctly handles the scenario where all cars are moving at the same speed. In that case, each car’s arrival time is strictly decreasing with its position, so each car becomes the leader of a new fleet, resulting in a fleet count equal to the number of cars.

Performance Optimizations

The solution achieves efficiency by reducing the problem to a single pass after sorting. Pairing positions with speeds using zip and sorting them in reverse order eliminates the need for additional data structures to track car ordering.

Computing arrival times with a list comprehension creates a compact array of floating-point values, allowing the subsequent loop to operate on simple numeric comparisons without recomputing the division each iteration.

The use of a single variable incoming to represent the current fleet’s arrival time avoids maintaining a stack or list of fleet times. This constant-space approach minimizes memory overhead while still correctly merging cars into fleets based on the monotonic property of arrival times after sorting.

By decrementing the fleet counter only when a car merges, the algorithm avoids extra bookkeeping for fleet members, resulting in a straightforward arithmetic update that runs in O(1) per iteration.

Overall, the combination of sorting, a precomputed arrival list, and a single scalar state variable yields a solution that processes the input with minimal computational and memory resources.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long race track where several cars are driving toward one finish line. The computer keeps track of how many groups of cars, called fleets, reach the finish line. First, the code looks at all the cars starting at different spots and calculates how long each one takes to reach the end. It starts by looking at the car closest to the finish line and works backward to the car furthest away.

Think of this like a line of cars on a highway. If a car behind is moving faster than the car in front of it, it will eventually catch up and drive right behind it, forming one single group. The code checks these arrival times one by one. If a car takes less time or the same amount of time to get to the finish line as the car ahead of it, that means it catches up and merges into the same group. When this happens, the total number of independent groups gets smaller. If a car takes longer to get to the finish line, it becomes the new leader of a different group. By the time every car is checked, the final count identifies how many distinct groups cross the line.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 0.96

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
bujosa Rust
charles-wangkai Java
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
bujosa Rust
charles-wangkai Java
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
zfang399 C++
30 links | 17 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

2 easy 2 medium
5 solutions   October 25, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality