853. Car Fleet
Asked at 11Google33Amazon31Microsoft25Bloomberg22Meta12Nutanix100Ripple82BNY Mellon75PhonePe64Waymo58Goldman Sachs21
Problem
n cars drive toward target on a one-lane road; car i starts at position[i] with speed[i]. A car can't pass the one ahead: when it catches up, they continue together at the slower speed as one fleet. Return how many fleets arrive at target (a car catching up exactly at target joins that fleet).
Example: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] → 3
Constraints: n ≤ 10⁵; positions are distinct.
Sort cars by position, closest to target first. Compute arrival time. A car behind that would arrive earlier or equal catches up and merges into the fleet ahead; otherwise it starts a new fleet.
Complexity: O(n log n).
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
fleets, slowest = 0, 0.0
for p, s in sorted(zip(position, speed), reverse=True):
t = (target - p) / s
if t > slowest: # can't catch the fleet ahead
fleets += 1
slowest = t
return fleets
assert Solution().carFleet(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3]) == 3
assert Solution().carFleet(100, [0, 2, 4], [4, 2, 1]) == 1
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, (a, b) -> position[b] - position[a]);
int fleets = 0;
double slowest = 0;
for (int i : idx) {
double t = (double) (target - position[i]) / speed[i];
if (t > slowest) { fleets++; slowest = t; }
}
return fleets;
}
}
func carFleet(target int, position []int, speed []int) int {
idx := make([]int, len(position))
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(a, b int) bool { return position[idx[a]] > position[idx[b]] }) // closest to target first
fleets, slowest := 0, 0.0
for _, i := range idx {
t := float64(target-position[i]) / float64(speed[i])
if t > slowest { // can't catch the fleet ahead
fleets++
slowest = t
}
}
return fleets
}