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?- A. 2
- B. 1
- C. 3
- 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
- Problem: Return the minimum number of parentheses to insert to make a string valid. python def minadd(s): open, add = 0, 0 for c in s: if…
- Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Design a set supporting insert, delete and getRandom (uniform) all in O(1) average time. Which design works?
- Problem: Rotate a linked list to the right by k places. python class N: def init(s, v, nx=None): s.v, s.nx = v, nx def rotate(h, k): n, t…
- Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part…