61 / 75
M

Car Fleet

#61
stackarraysorting+1

Sort cars by position, calculate time to target, use stack to count fleets (slower cars create new fleets).

Example:

Input:target=12, position=[10,8,0,5,3], speed=[2,4,1,1,3]
Output:3 (fleets reach at times 1, 3, 12)

Common Mistakes:

  • Not sorting by position first
  • Using integer division instead of double (loses precision)
  • Wrong sorting order (should be descending from target)
  • Overcomplicating with actual stack when counter suffices

Notes:

Sort by position then track time. If slower car ahead, faster car joins its fleet. Time O(n log n), Space O(n).

61/75
Car Fleet