Queue Reconstruction by Height

Put a shuffled list of people back into line, given each person's height and how many people at least as tall stand in front.

People stand in a queue, and each person is described by a pair [h, k]: h is their height, and k is how many people in front of them have a height greater than or equal to h. Given these pairs in a shuffled order as the array people, rebuild the queue and return it, front of the queue first. The pairs always describe a queue that can really exist.

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]]
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]]
Solution

The Idea

Imagine a line of people where everyone has a note in their pocket. The note says their height and how many people ahead of them are at least as tall. Then the line breaks up, and only the notes are left. Can we put everyone back in their place?

Check the notes against the answer to Example 1. The person [6, 1] stands fourth, behind 5, 7 and 5. Only the 7 is at least 6 tall, so their count is 1, as the note says. The person [4, 4] stands fifth, and all four people ahead of them are taller, so their count is 4.

Look at [6, 1] again. The two people of height 5 in front of them made no difference to their count. A shorter person is invisible to a taller person's count, wherever they stand. That raises the question: in which order should people go back into the line, so that each count is easy to meet?

Start with the tallest. When someone joins, everyone already in the line is at least as tall as them, so all of them count. A person with count k then simply goes to position k, counting from 0, with exactly k people in front. Everyone who joins later is shorter, so they cannot change that count. Look at the picture below.

Example 1 built person by person, tallest first. Each row inserts the next person at the position equal to their k, and the new person is highlighted. The last row is the answer [5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1].

Each row places one more person, and the highlighted box is the new one. In the row labelled "[6, 1] at position 1", the 6 goes in behind [7, 0] and pushes [7, 1] one place back. [7, 1] still has exactly one person of height 7 or more in front, because the 6 does not count for a 7.

The two people of height 7 show how to break a tie. They count each other, so [7, 0] must already stand in the line when [7, 1] looks for its position 1. Among equal heights, the smaller count goes first. In the last row, [4, 4] goes to position 4, and the line reads exactly like the answer.

Each person is put in their final spot the moment they come up, using only the people placed so far, and nobody is moved by hand afterwards. Placing each person straight at the position their count names, tallest first, without trying other orders, is what makes this a greedy solution.

Solution Approach

Turning that idea into code means three things: seeing why trying every order is not needed, choosing the order in which people are placed, and choosing what holds the growing line.

Why not try every order

Could we try every way to arrange the people and check all the counts? Six people can stand in 720 different orders, and twelve people in nearly 480 million. The tallest-first order goes straight to the answer instead, placing each person once.

The order to place people in

Which person goes first? Sort the people by height, tallest first, and break ties by count, smallest first. For Example 1 that gives [7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4], the order of the rows in the picture.

Shortest first does not work. In Example 1, [4, 4] would then come up first and ask for position 4 in an empty line, with nobody yet to stand in front of them.

Holding the growing line

What should hold the line while people join? Each person goes into the middle, so the people behind them must move back one place. A Java ArrayList does that with add(index, element): it shifts everything from index onward one place back and puts the new element at index. Here each element is one person's int[] pair.

Java Solution

The method reconstructQueue works in these steps:

  1. First, sort people with Arrays.sort and a comparator. When the heights a[0] and b[0] differ, b[0] - a[0] puts the taller person first. When they are equal, a[1] - b[1] puts the smaller count first.
  2. Create queue, an empty ArrayList<int[]> that holds the line as it grows.
  3. Loop over the sorted people. Each person p goes in with queue.add(p[1], p), at the position given by their count p[1].
  4. When the loop is done, turn queue back into an int[][] with toArray(new int[0][]) and return it.

The main method runs both examples, a line where everyone has the same height, a line where each person has a count of 0, a single person, and nobody at all.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class QueueReconstructionByHeight {

    public static int[][] reconstructQueue(int[][] people) {
        // tallest first; for equal heights, the smaller k first
        Arrays.sort(people, (a, b) -> a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]);
        List<int[]> queue = new ArrayList<>();
        for (int[] p : people) {
            queue.add(p[1], p);   // everyone already placed is at least as tall
        }
        return queue.toArray(new int[0][]);
    }

    public static void main(String[] args) {
        int[][][] inputs = {
            {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}},
            {{6, 0}, {5, 0}, {4, 0}, {3, 2}, {2, 2}, {1, 4}},
            {{5, 2}, {5, 0}, {5, 1}},          // everyone the same height
            {{1, 0}, {2, 0}, {3, 0}},          // nobody taller in front of anyone
            {{4, 0}},
            {}
        };
        for (int[][] people : inputs) {
            System.out.println(Arrays.deepToString(reconstructQueue(people)));
        }
    }
}

Running it prints:

Output
[[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
[[4, 0], [5, 0], [2, 2], [3, 2], [1, 4], [6, 0]]
[[5, 0], [5, 1], [5, 2]]
[[1, 0], [2, 0], [3, 0]]
[[4, 0]]
[]

The line [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]] matches the last row of the picture, and the next line matches the answer to Example 2. In [[5, 0], [5, 1], [5, 2]], everyone is 5 tall, so the tie rule alone decides the order: each person joins at the back, behind everyone with a smaller count.

Now look at [[1, 0], [2, 0], [3, 0]]. Every count is 0, so each person goes to the front as they join: first 3, then 2 in front of it, then 1 in front of both. The line ends up shortest to tallest, and nobody has a taller person ahead. The empty input gives [], because the loop never runs.

The tie rule matters. With equal heights sorted by the larger count first, the pairs [[7, 0], [7, 1]] put [7, 1] first, and inserting it at position 1 of the empty list throws IndexOutOfBoundsException: Index: 1, Size: 0.

One side effect: Arrays.sort reorders the caller's people array. If the caller still needs the shuffled order, pass a copy.

Complexity

The work is one sort plus one insert per person, and the inserts cost the most.

  • Time: O(n²), because each of the n inserts into queue can shift up to n people already in the line, while the sort takes only O(n log n).
  • Space: O(n), because queue and the returned array each hold one reference per person, and sorting an array of arrays can use up to O(n) more.

A custom sort order that makes a single greedy pass work is also the heart of Largest Number.