Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Reconstruct a queue of people (h, k) where k = number of people in front with height ≥ h.

Problem: Reconstruct a queue of people (h, k) where k = number of people in front with height ≥ h.
def rebuild(people):
    people.sort(key=lambda p: (-p[0], p[1])); q = []
    for p in people: q.insert(p[1], p)
    return q
print(rebuild([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]))
What is printed?
  1. A. [[7, 0], [5, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
  2. B. [[5, 0], [7, 0], [6, 1], [5, 2], [4, 4], [7, 1]]
  3. C. [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
  4. D. [[4, 4], [5, 0], [5, 2], [6, 1], [7, 0], [7, 1]]

Correct answer: C. [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]

Insert tallest first (ties by k): when a person is inserted at index k, everyone already placed is at least as tall, so exactly k of them are in front; shorter people inserted later do not affect that count. O(n²) with list inserts.

More Coding Interview Problems questions

Exams that ask this topic