MEDIUM Greedy / Sorting
406. Queue Reconstruction by Height
š Problem
You are given an array of people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represented by the input array. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).
š§ Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- ā¢Array methods (`push`, `pop`, `shift`, `slice`)
- ā¢Object/Map/Set usage patterns
- ā¢Function parameter and return typing
- ā¢Level-order traversal
- ā¢Queue discipline
- ā¢Shortest-step interpretation
Logical Thinking Concepts
- ā¢Define invariants before coding
- ā¢Check edge cases first (`[]`, single element, duplicates)
- ā¢Estimate time/space before implementation
- ā¢Apply BFS reasoning pattern
- ā¢Apply Greedy reasoning pattern
š” Approach
- ā Sort people by height descending, and by k ascending
- ā Insert each person at index k in result array
- ā This ensures there are exactly k taller/equal people in front
- ā Time: O(n²), Space: O(n)
š ļø Hints & Pitfalls
Hints
- ā¢Sort people by height descending, and by k ascending
- ā¢Insert each person at index k in result array
- ā¢This ensures there are exactly k taller/equal people in front
Common Pitfalls
- ā¢Time: O(n²), Space: O(n)
š§Ŗ Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
reconstructQueue([[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]); Expected:
[4, 0, 2, 1, 0, 1] Test Case 2
Not run Input:
reconstructQueue([[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]); Expected:
[4, 2, 2, 0, 0, 0] Test Case 3
Not run Input:
reconstructQueue([[0]]); Expected:
[null] š Code Editor
š¤ Output