Queue Reconstruction by Height - Problem

You are given an array of people, people, which represents the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the i-th 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 people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the j-th person in the queue (queue[0] is the person at the front of the queue).

Input & Output

Example 1 — Basic Queue Reconstruction
$ Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
💡 Note: Person [5,0] has 0 people ≥ 5 in front (correct). Person [7,0] has 0 people ≥ 7 in front (correct). Person [5,2] has 2 people ≥ 5 in front: [5,0] and [7,0] (correct). And so on for all positions.
Example 2 — Simple Case
$ Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]
💡 Note: Each person is placed to satisfy their k-constraint: [4,0] needs 0 people ≥4 in front, [5,0] needs 0 people ≥5 in front, etc.
Example 3 — Same Heights
$ Input: people = [[7,0],[7,1],[6,1]]
Output: [[7,0],[6,1],[7,1]]
💡 Note: [7,0] goes first with 0 people ≥7 in front. [6,1] goes next with 1 person ≥6 in front ([7,0]). [7,1] goes last with 1 person ≥7 in front ([7,0]).

Constraints

  • 1 ≤ people.length ≤ 2000
  • 0 ≤ hi ≤ 106
  • 0 ≤ ki < people.length
  • It is guaranteed that the queue can be reconstructed

Visualization

Tap to expand
Queue Reconstruction by HeightInput (Unordered):[7,0][4,4][7,1][5,0]Sort & InsertOutput (Ordered Queue):[5,0][7,0][5,2][6,1]0 ≥ 50 ≥ 72 ≥ 51 ≥ 6Each person has exactly k people ≥ their height in front
Understanding the Visualization
1
Input
Array of [height, count] pairs representing people
2
Process
Sort by height and insert at correct positions
3
Output
Properly ordered queue satisfying all constraints
Key Takeaway
🎯 Key Insight: Sort by height descending, then insert each person at their k-th position since taller people don't affect shorter people's count
Asked in
Google 25 Amazon 18 Facebook 12 Microsoft 10
217.0K Views
Medium Frequency
~25 min Avg. Time
6.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen