Queue Reconstruction by Height - Problem
Queue Reconstruction by Height presents a fascinating puzzle of ordering people in a queue based on partial information.
You're given an array
•
•
Your task is to reconstruct the original queue order that satisfies all these constraints.
Example: If someone is
The challenge lies in figuring out the correct positioning when you only have these indirect clues about everyone's relative positions!
You're given an array
people where each element people[i] = [h_i, k_i] represents:•
h_i: the height of the i-th person•
k_i: the number of people in front who are taller or equal in heightYour task is to reconstruct the original queue order that satisfies all these constraints.
Example: If someone is
[7, 1], they're 7 units tall with exactly 1 person of height ≥7 in front of them.The challenge lies in figuring out the correct positioning when you only have these indirect clues about everyone's relative positions!
Input & Output
example_1.py — Basic Case
$
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] goes first (height 5, 0 taller in front). Person [7,0] goes second (height 7, 0 taller in front). Person [5,2] goes third (height 5, needs 2 taller people in front: [7,0] and upcoming [6,1]).
example_2.py — 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:
Starting with tallest: [6,0] at pos 0, [5,0] at pos 0 (pushes 6 right), [4,0] at pos 0 (pushes others right). Then shorter people fill their k positions.
example_3.py — Single Person
$
Input:
people = [[1,0]]
›
Output:
[[1,0]]
💡 Note:
With only one person, they must be at the front with 0 taller people in front of them.
Visualization
Tap to expand
Understanding the Visualization
1
Gather Information
Each person has a card: [height, count_of_taller_in_front]
2
Sort by Height
Arrange cards from tallest to shortest people
3
Seat Tallest First
Place tallest people at their exact required positions
4
Insert Others
Shorter people slide into gaps without affecting tall people's counts
Key Takeaway
🎯 Key Insight: Since shorter people are 'invisible' to taller people when counting, we can safely place all tall people first at their exact positions, then insert shorter people without disrupting the tall people's constraints.
Time & Space Complexity
Time Complexity
O(n! × n)
n! permutations, each taking O(n) time to validate
⚠ Quadratic Growth
Space Complexity
O(n)
Space for storing current permutation and result
⚡ Linearithmic Space
Constraints
- 1 ≤ people.length ≤ 2000
- 0 ≤ hi ≤ 106
- 0 ≤ ki < people.length
- It is guaranteed that the queue can be reconstructed
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code