Queue Reconstruction by Height solution explained
Queue Reconstruction by Height is solved by sorting people from tallest to shortest, breaking ties by the smaller count, and inserting each person at the index equal to their count. Taller people never notice shorter ones, so each insertion is final, and the whole method runs in O(n²) time with a plain list.
By Evin JohnPublished 7 min read
Restating the task
A group of people stood in a single line, then scattered. For each person you know two numbers: their height h and a count k, the number of people who were standing ahead of them with a height greater than or equal to h. You get these pairs in a random order. Put them back into a line where every person's count is true again. Inputs are promised to come from some real line, so a valid answer exists.
| Input pairs (shuffled) | Rebuilt line | Check one person |
|---|---|---|
| [[4,3], [7,0], [5,2], [6,0], [4,1]] | [[6,0], [4,1], [7,0], [4,3], [5,2]] | The second 4 has 6, 4 and 7 ahead of it, all at least 4 tall, so its count is 3. |
| [[2,0], [2,1], [2,2]] | [[2,0], [2,1], [2,2]] | Equal heights count each other, so they line up by count. |
| [[9,0], [3,0], [5,0]] | [[3,0], [5,0], [9,0]] | Every count is zero, which forces strictly rising heights. |
Two details trip people up in the statement itself. First, the count includes people of equal height, not only taller ones. Second, the count looks only forward, toward the front of the line. Confirm both with the interviewer before writing anything.
Where this problem fits
This is a greedy problem in disguise. The key question an interviewer wants you to ask is: which people can I place without knowing anything about the others? The answer, the tallest ones, is the insight that unlocks it. It also tests whether you can reason about list insertion cost honestly, since the obvious implementation is quadratic and that is usually accepted.
Slow approach: try every ordering
You can always generate every permutation of the pairs and keep the first one where every count checks out. Checking one ordering costs O(n²) if you count by scanning, and there are n! orderings, so this dies at around ten people. It is still worth writing the checker, because you will reuse it to test the fast version.
from itertools import permutations
def line_is_valid(line):
for i, (h, k) in enumerate(line):
ahead = sum(1 for j in range(i) if line[j][0] >= h)
if ahead != k:
return False
return True
def rebuild_by_search(people):
for order in permutations(people):
if line_is_valid(order):
return [list(p) for p in order]
return NoneMain approach: tallest first, insert at the count
Think about the tallest person in the group. Nobody else can affect their count except people of the same height, because shorter people are invisible to them. So if you place tall people first, they form a correct partial line, and later, shorter arrivals cannot break it. Now take the next person, who is no taller than anyone placed so far. Everyone already in the line counts toward their k. To have exactly k of them in front, insert this person at index k. Any people inserted after them are shorter, so they do not change this person's count either.
Equal heights need the tie-break. Two people of height 4 with counts 1 and 3 must go in that order. If the person with count 3 is inserted first and the one with count 1 second, the second insertion lands in front and adds one to the first person's count. Sorting equal heights by ascending count keeps every later same-height insertion behind the earlier ones.
def rebuild_queue(people):
line = []
for h, k in sorted(people, key=lambda p: (-p[0], p[1])):
line.insert(k, [h, k])
return linefunction rebuildQueue(people) {
const order = people.slice().sort((a, b) => b[0] - a[0] || a[1] - b[1]);
const line = [];
for (const [h, k] of order) {
line.splice(k, 0, [h, k]);
}
return line;
}Trace the first table row. Sorted, the pairs are (7,0), (6,0), (5,2), (4,1), (4,3). The line grows as [7], then [6,7], then [6,7,5], then [6,4,7,5], and finally [6,4,7,4,5]. Read the counts back and every one matches.
A second route: shortest first, fill empty seats
You can also go the other way. Make an array of n empty seats and process people from shortest to tallest, with equal heights ordered by larger count first. Each person sits in the empty seat that has exactly k empty seats before it, because those empty seats will later hold people who are at least as tall. It is still O(n²) with a linear scan, but it is the version that a Fenwick tree or segment tree can speed up to O(n log n), since finding the k-th empty seat becomes a prefix-sum search.
def rebuild_by_seats(people):
n = len(people)
seats = [None] * n
for h, k in sorted(people, key=lambda p: (p[0], -p[1])):
empty_seen = 0
for i in range(n):
if seats[i] is None:
if empty_seen == k:
seats[i] = [h, k]
break
empty_seen += 1
return seatsTime and space
| Method | Time | Extra space | Note |
|---|---|---|---|
| Every permutation | O(n! · n²) | O(n) | Reference only |
| Tallest first with list insert | O(n²) | O(n) | Sorting is O(n log n); the inserts dominate |
| Shortest first with empty seats | O(n²) | O(n) | Drops to O(n log n) with a Fenwick tree |
Be precise when you state the cost. Python's list insert and JavaScript's splice shift every element after the insertion point, so each one is O(n) in the worst case. Calling the main solution O(n log n) because it starts with a sort is a common slip.
Edge cases
- No people at all: return an empty list.
- One person: their count must be 0 and the line is just them.
- Everyone the same height: the counts are 0, 1, 2 and so on, and the answer is the pairs sorted by count.
- Every count zero: the line must rise strictly in height from front to back.
- Very tall person with a large count: they are inserted early, then shorter people slide in front without changing their count.
Common mistakes
- Sorting by height ascending and inserting at k. Shorter people placed first get their counts broken by every taller person inserted ahead of them.
- Sorting equal heights by count descending in the tallest-first method.
- Reading the count as strictly taller. People of equal height count.
- Sorting the input array in place in JavaScript and surprising the caller. Copy with slice first, or say that you mutate.
- Inserting a reference to the same pair object and later editing it. Build a fresh pair or leave pairs untouched.
Follow-ups an interviewer may add
- Make it faster than quadratic. Use the shortest-first variant with a Fenwick tree over empty seats and binary search for the k-th free position.
- Validate the input. Run the checker above after rebuilding; if it fails, the input did not come from a real line.
- Strictly taller instead of at least as tall. Flip the tie-break so that equal heights are processed with larger counts first in the tallest-first method, and test it.
Explaining the idea
Fictional example
- Candidate
- A short person is invisible to everyone taller, so the tallest people can be placed without worrying about anyone else.
- Candidate
- I sort tallest first, ties by smaller count, and insert each person at index k. Everyone already in the line is at least as tall, so exactly k of them end up ahead.
- Candidate
- Inserting into a list is linear, so overall it is O(n²). If that is too slow, I can switch to filling empty seats shortest first with a Fenwick tree.
Neighbors in this set
Lemonade Change is a smaller greedy problem where the proof is an exchange argument, and Minimum Deletions to Make Character Frequencies Unique also works by processing the largest values first. The data structure interview questions page covers the list and tree costs that decide which version you choose.
Practicing with Natively
In a practice session, Natively can read this problem from a screenshot and propose an approach and code, which you can hold up against your own after a first attempt. Because it also transcribes a mock interview on your computer, you can review whether you justified the tie-break or only stated it. See how an AI interview assistant fits into a study routine on Mac or Windows.
Questions people ask
How do you solve Queue Reconstruction by Height?
Sort people by height from tallest to shortest, with equal heights ordered by smaller count first. Then insert each person into a list at the index equal to their count. The result is the original line.
Why sort by height in descending order?
Shorter people never affect a taller person's count. Placing the tallest first means every later insertion is of someone shorter or equal, so it cannot break counts that are already correct.
What is the time complexity?
O(n²) with a list, because each insertion shifts the elements behind it. Sorting adds O(n log n). A shortest-first version with a Fenwick tree over empty seats brings it to O(n log n).
Why do equal heights need a tie-break?
People of equal height count each other. Inserting the smaller count first keeps later same-height people behind it, so its count stays right.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
