AlgoInsight

DSA problem

Queue Reconstruction by Height

MediumGreedyPattern: Greedytop600AmazonGoogleMicrosoftAdobeBloomberg

You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [h_i, k_i] represents the i-th person of height h_i with exactly k_i other people in front who have a height greater than or equal to h_i. Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [h_j, k_j] is the attributes of the j-th person in the queue.

A brute-force search over all n! permutations is hopeless even for moderate n. The structural fact that unlocks a greedy approach is this: once people taller-or-equal than a given person have been placed, inserting that person somewhere into the existing sequence does not change anyone's k_i value, because all the smaller people that will be inserted later are invisible to the taller ones' k count.

So the order in which we should insert people is "tallest first, breaking ties by smaller k_i first". Sort people in descending order of height; for equal heights, ascending order of k_i. Now process people one by one and insert each at position k_i in a growing list. Because everyone already in the list is at least as tall as the current person, inserting at index k_i automatically guarantees k_i taller-or-equal people in front.

This trades the brute combinatorial search for a sort plus n array insertions: O(n log n) to sort and O(n^2) worst-case for the inserts (each insert into the middle of an array shifts O(n) elements). It is the standard greedy reconstruction and is simple to argue correct by induction on insertion order.

Examples

Example 1
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]]
Explanation: After sorting by descending height (ties by ascending k) we insert in order [7,0], [7,1], [6,1], [5,0], [5,2], [4,4], each at index k. The final ordering satisfies every person's k count.
Example 2
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]]
Explanation: Tallest-first insertion produces a queue where every person has the required number of taller-or-equal people in front. Note that even though [6,0] is the tallest, by the time it is inserted (at index 0) the rest of the queue is already shorter, so the result is valid.
Example 3
Input: people = [[1,0]]
Output: [[1,0]]
Explanation: A single person trivially satisfies the constraint with no one in front.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

greedyarraysortingbinary-indexed-tree

Browse all DSA problems