Queue Reconstruction by Height (LeetCode 406): Solution and Explanation
Each person is described by a pair [h, k]: their height and how many people at least as tall stand in front of them. The list is shuffled, and you must return the queue order that makes every pair true.
Watch it run step by step
Try your own input and write the code →Intuition
Trying permutations is out of the question, so look for an order in which to place people where each placement is easy. The shortest person is tricky to place first, because their k counts people who have not been placed yet. The tallest people, on the other hand, only care about each other, since nobody shorter is counted in their k.
That suggests placing people from tallest to shortest. When you reach someone, everyone already in the line is at least as tall as them, so inserting them at index k puts exactly k taller or equal people ahead. And anyone inserted afterwards is shorter, so they are invisible to this person's count and cannot break it, no matter where they go. Insertions shift people to the right, but a shift only moves someone behind a shorter person, which leaves their count of taller people ahead unchanged.
Ties need one more rule. Among people of equal height, place the one with the smaller k first. Otherwise inserting someone with a larger k first and then a same-height person with smaller k in front of them would push the first one's count up by one.
Approach: Sort tall first, then insert at index k
- Sort
peopleby height descending, and for equal heights bykascending, using the key(-h, k). - Create an empty
resultlist. - For each person in sorted order, insert them into
resultat positionk. - Because everyone already present is at least as tall, the insertion makes their
kexactly right. - Return
resultonce everyone has been placed. No final check is needed, since every insertion was correct when it was made and later insertions never invalidate it.
Step-by-step example
people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
- Sorted order is
[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]. - Insert
[7,0]at 0 and[7,1]at 1, giving[[7,0],[7,1]]. Insert[6,1]at 1:[[7,0],[6,1],[7,1]]. - Insert
[5,0]at 0:[[5,0],[7,0],[6,1],[7,1]]. Insert[5,2]at 2:[[5,0],[7,0],[5,2],[6,1],[7,1]]. - Insert
[4,4]at 4:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]. - Check
[4,4]: four taller people (5, 7, 5, 6) stand ahead of it. Check[7,1]: only[7,0]is as tall ahead of it. Every pair holds.
Code: Python, Java, C++
1class Solution:
2 def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
3 # Sort by height desc, then by k asc
4 people.sort(key=lambda x: (-x[0], x[1]))
5
6 result = []
7 for person in people:
8 # Insert at index k
9 result.insert(person[1], person)
10
11 return result1class Solution {
2 public int[][] reconstructQueue(int[][] people) {
3 // Sort by height desc, then by k asc
4 Arrays.sort(people, (a, b) -> a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]);
5
6 List<int[]> result = new ArrayList<>();
7 for (int[] person : people) {
8 // Insert at index k
9 result.add(person[1], person);
10 }
11
12 return result.toArray(new int[people.length][]);
13 }
14}1class Solution {
2public:
3 vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
4 // Sort by height desc, then by k asc
5 sort(people.begin(), people.end(), [](auto& a, auto& b) {
6 return a[0] != b[0] ? a[0] > b[0] : a[1] < b[1];
7 });
8
9 vector<vector<int>> result;
10 for (auto& person : people) {
11 // Insert at index k
12 result.insert(result.begin() + person[1], person);
13 }
14
15 return result;
16 }
17};Time and space complexity
O(n²)
Sorting costs O(n log n), but each list insertion shifts up to n elements, so the n insertions dominate at O(n²).
O(n)
The result list holds all n people; the sort uses at most O(n) auxiliary space.
Other approaches
Shortest first with empty slots (time O(n²), space O(n))
Sort by height ascending (and k descending for ties), then place each person in the k-th empty slot of a fixed array, counting empty slots as positions for taller people. Same quadratic cost with a simple scan.
Binary indexed tree for slots (time O(n log² n), space O(n))
Use the shortest-first idea, but find the k-th empty slot with a Fenwick tree and binary search instead of a scan, which drops the cost for large inputs.
Common mistakes
- Sorting ties by
kdescending. Then a later same-height person inserted in front shifts an earlier one and breaks its count. - Inserting shortest people first with the same insert-at-k rule. Their
kcounts taller people who have not been placed yet, so the index is wrong. - Assigning
result[k] = personinstead of inserting. Assignment overwrites someone already placed instead of shifting them right. - Claiming the solution is O(n log n). The sort is, but list insertion in the middle is linear.
Frequently asked questions
Why sort by height descending in queue reconstruction?
Taller people do not count shorter ones, so if you place tallest first, each new person only needs to see people already placed. Inserting at index k then sets their count exactly.
Why sort equal heights by k ascending?
Equal heights count each other. Placing the smaller k first means each later same-height person is inserted at a larger index, behind the earlier one, so the earlier person's count is never disturbed.
What is the time complexity of queue reconstruction by height?
O(n²) because each of the n insertions into a list can shift up to n elements. Sorting adds only O(n log n).
Can it be done faster than O(n²)?
Yes, with a Fenwick or segment tree to find the k-th free slot in logarithmic time, giving about O(n log² n) or O(n log n), though the simple insertion method is fine for typical sizes.