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?
  1. A. [[3, 0], [5, 0], [6, 0], [4, 1], [3, 2], [2, 3]]
  2. B. [[3, 0], [6, 0], [5, 0], [3, 2], [4, 1], [2, 3]]
  3. C. [[5, 0], [6, 0], [3, 0], [4, 1], [3, 2], [2, 3]]
  4. 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

Exams that ask this topic