Queue Reconstruction by Height (LeetCode 406): Solution and Explanation

Medium
Array
Greedy
Binary Indexed Tree
Segment Tree
Sorting

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Sort people by height descending, and for equal heights by k ascending, using the key (-h, k).
  2. Create an empty result list.
  3. For each person in sorted order, insert them into result at position k.
  4. Because everyone already present is at least as tall, the insertion makes their k exactly right.
  5. Return result once 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]]
  1. Sorted order is [7,0], [7,1], [6,1], [5,0], [5,2], [4,4].
  2. 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]].
  3. 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]].
  4. Insert [4,4] at 4: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]].
  5. 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 result

Time and space complexity

Time

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²).

Space

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 k descending. 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 k counts taller people who have not been placed yet, so the index is wrong.
  • Assigning result[k] = person instead 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.