SDE & MLE Prep

406. Queue Reconstruction by Height

Problem

People in a queue were shuffled; people[i] = [h, k] says person i has height h and exactly k people in front of them are at least as tall. Reconstruct and return the queue.

Example: [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] → [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]

Constraints: up to 2000 people.

Sort by height descending, then k ascending. Insert each person at index k: everyone already placed is taller or equal, so exactly k of them are in front, and shorter people inserted later don't affect it.

sorted: [7,0] [7,1] [6,1] [5,0] [5,2] [4,4]
insert: [7,0]
        [7,0] [7,1]
        [7,0] [6,1] [7,1]
        [5,0] [7,0] [6,1] [7,1]
        [5,0] [7,0] [5,2] [6,1] [7,1]
        [5,0] [7,0] [5,2] [6,1] [4,4] [7,1]

Complexity: O(n²).

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        res = []
        for h, k in sorted(people, key=lambda p: (-p[0], p[1])):
            res.insert(k, [h, k])
        return res