Leetcode 853: Car Fleet

grid47
grid47
Exploring patterns and algorithms
Aug 13, 2024 5 min read

You are given several cars starting at different positions along a road. Each car has a specific speed and is trying to reach a target destination. A car cannot pass another car, but it can catch up and travel at the speed of the slower car. Cars that travel together form a fleet. Your task is to determine the number of car fleets that will reach the target.
Problem
Approach
Steps
Complexity
Input: You are given the target distance, an array of car positions, and an array of car speeds.
Example: Input: target = 15, position = [12, 5, 2, 9], speed = [3, 4, 2, 5]
Constraints:
• n == position.length == speed.length
• 1 <= n <= 10^5
• 0 < target <= 10^6
• 0 <= position[i] < target
• All the values of position are unique.
• 0 < speed[i] <= 10^6
Output: Return the number of car fleets that will arrive at the target.
Example: Output: 2
Constraints:
Goal: The goal is to find how many fleets will form by considering each car's starting position and speed, and determining if it will catch up to others.
Steps:
• Step 1: Calculate the time it takes for each car to reach the target.
• Step 2: Sort the cars by their starting position in descending order.
• Step 3: Iterate through the sorted list of cars, comparing the time for each car to reach the target with the previous car's time.
• Step 4: If a car reaches the target faster than the previous car, it forms a new fleet. Otherwise, it joins the previous fleet.
Goal: The positions of the cars are guaranteed to be unique and within the range of the target.
Steps:
• The array of positions will be sorted before applying the logic.
Assumptions:
• Cars with the same position cannot exist.
Input: Input: target = 10, position = [7, 3, 0, 5], speed = [1, 2, 3, 4]
Explanation: In this example, the car starting at position 0 (speed 3) reaches the target before the car starting at position 3 (speed 2), but after the car starting at position 7 (speed 1). The car starting at position 5 (speed 4) forms a fleet with the car starting at position 3 and moves at the same speed. Therefore, there are 2 fleets.

Input: Input: target = 100, position = [0, 10, 20, 30], speed = [10, 5, 2, 1]
Explanation: In this example, the car starting at position 0 (speed 10) forms a fleet by itself. The cars starting at positions 10, 20, and 30 form a single fleet because each catches up to the previous one.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus