mediumGreedySortingGreedy

Queue Reconstruction by Height

mediumTime: O(n^2)Space: O(n)

Recognize the pattern

reconstruct queue by heighttaller people don't see shorter ones aheadinsert by height

Brute force idea

The naive version of Queue Reconstruction by Height sounds like this: Try all permutations and check validity. Factorial. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The deeper shift in Queue Reconstruction by Height is this: Sort by height descending (ties by k ascending). Insert each person at index k in the result. Taller people are placed first, so inserting at index k naturally puts exactly k taller people ahead. for insertions. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Queue Reconstruction by Height is one steady idea: When you insert a person of height h at index k, all previously inserted people are ≥ h (sorted descending). So exactly k of them are ahead — the k constraint is automatically satisfied. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

A common way to get lost in Queue Reconstruction by Height is this: Sorting by height ascending — that doesn't work because inserting shorter people first disrupts the positions of taller people added later. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Greedy Pattern