Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Cars drive toward a target on a one-lane road. A car that catches a slower car ahead joins it as a fleet (moving at the slower speed). How many fleets arrive?

Problem: Cars drive toward a target on a one-lane road. A car that catches a slower car ahead joins it as a fleet (moving at the slower speed). How many fleets arrive?
def fleets(target, pos, speed):
    cars = sorted(zip(pos, speed), reverse=True)
    stack = []
    for p, s in cars:
        t = (target - p) / s
        if not stack or t > stack[-1]: stack.append(t)
    return len(stack)
print(fleets(20, [0, 4, 9, 15], [5, 2, 3, 1]))
What is printed?
  1. A. 2
  2. B. 1
  3. C. 3
  4. D. 4

Correct answer: A. 2

Arrival times if alone: car at 15 → 5.0, at 9 → 3.67, at 4 → 8.0, at 0 → 4.0. Going from the front, the car at 9 would arrive earlier than 15's car, so it joins that fleet; 4 is slower (8.0), starting a new fleet that the car at 0 (4.0) then catches. Two fleets.

More Coding Interview Problems questions

Exams that ask this topic