Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Delivery vans drive towards a depot at 20 km; a faster van that catches a slower one ahead must slow down and they arrive as one fleet. Count the fleets.

Problem: Delivery vans drive towards a depot at 20 km; a faster van that catches a slower one ahead must slow down and they arrive as one fleet. Count the fleets.
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, [2, 6, 10, 15, 17], [3, 2, 2, 1, 1]))
What is printed?
  1. A. 2
  2. B. 5
  3. C. 3
  4. D. 4

Correct answer: C. 3

Process vans from closest to the depot; each van's solo arrival time is (20 − p)/s. A van that would arrive no later than the fleet just ahead joins it; a strictly later time starts a new fleet. Times from the front: 3, 5, 5, 7, 6 → fleets at 3, 5 (the van at 10 joins), 7 (the van at 2, time 6, joins it) → 3. Sorting by speed or position alone ignores catching up. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic