Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Each person is [h, k]: height h, and exactly k people in front are at least as tall. Rebuild the queue (sort tallest first, insert each at index k).
Problem: Each person is [h, k]: height h, and exactly k people in front are at least as tall. Rebuild the queue (sort tallest first, insert each at index k).
def rebuild(p):
p.sort(key=lambda x: (-x[0], x[1])); q = []
for x in p: q.insert(x[1], x)
return q
print(rebuild([[5, 0], [3, 2], [6, 0], [3, 0], [4, 1], [2, 3]]))What is printed?- A. [[3, 0], [5, 0], [6, 0], [4, 1], [3, 2], [2, 3]]
- B. [[3, 0], [6, 0], [5, 0], [3, 2], [4, 1], [2, 3]]
- C. [[5, 0], [6, 0], [3, 0], [4, 1], [3, 2], [2, 3]]
- D. [[3, 0], [5, 0], [3, 2], [2, 3], [4, 1], [6, 0]]
Correct answer: D. [[3, 0], [5, 0], [3, 2], [2, 3], [4, 1], [6, 0]]
Inserting taller people first means a shorter person inserted later at index k never disturbs anyone's count. Order of insertion: [6,0], [5,0], [4,1], [3,0], [3,2], [2,3], giving the unique valid queue [[3, 0], [5, 0], [3, 2], [2, 3], [4, 1], [6, 0]].
More Coding Interview Problems questions
- Problem: 2n people must be split so n fly to city A and n to city B; costs[i] = [costA, costB]. Minimise total cost (sort by costA −…
- Problem: Can the cards be split into groups of W consecutive values? python from collections import Counter def straights(hand, W): if…
- Problem: Report the median of every window of size k (sorted-list version with bisect). python from bisect import insort, bisectleft def…
- Problem: A single-threaded CPU receives tasks [enqueueTime, processingTime]. When idle it runs the available task with the shortest…
- Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs. python st, out = [], [] def…
- Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor. python def…