KatInterview

406. Queue Reconstruction by Height

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to reconstruct a queue from a list of people, where each person is described by their height h and a number k. k represents the count of people standing in front of this person who have a height greater than or equal to h. The core challenge is to find an ordering of all people that simultaneously satisfies every person's k constraint.

Solution

Queue Reconstruction by Height in Python

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        # Sort people based on a custom key.
        # 1. Primary key: height in descending order (using negative height).
        # 2. Secondary key: k value in ascending order.
        # For example, [7,0] becomes (-7, 0) and [6,1] becomes (-6, 1).
        # Python's tuple comparison will sort by the first element, then the second.
        # So, (-7, 0) < (-6, 1) as -7 < -6.
        people.sort(key=lambda x: (-x[0], x[1]))
        
        result = []
        # Iterate through the sorted people and insert them into the result list
        # at the index specified by their k value.
        for p in people:
            # p[1] is the k value, which is the insertion index.
            # When we insert a person, everyone already in 'result' is taller or of equal height.
            # So, inserting at index p[1] places them correctly among these people.
            result.insert(p[1], p)
            
        return result

Queue Reconstruction by Height in Java

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        // Sort the people array based on a custom comparator.
        // 1. Primary key: height in descending order.
        // 2. Secondary key: k value in ascending order.
        Arrays.sort(people, (a, b) -> {
            if (a[0] != b[0]) {
                // Sort by height descending (taller person first)
                return b[0] - a[0];
            } else {
                // If heights are equal, sort by k ascending (smaller k first)
                return a[1] - b[1];
            }
        });

        // Use a List for easy insertion at a specific index.
        // LinkedList is chosen here, though ArrayList would also work with the same time complexity for this operation.
        List<int[]> resultList = new LinkedList<>();
        for (int[] p : people) {
            // Insert person p at the index specified by p[1] (k value).
            // When we insert a person, all people already in the list are taller or of the same height.
            // So, p[1] is the correct position relative to these people.
            resultList.add(p[1], p);
        }

        // Convert the List back to a 2D array.
        return resultList.toArray(new int[people.length][2]);
    }
}

Queue Reconstruction by Height in C++

class Solution {
public:
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        // Sort people based on a custom comparator.
        // 1. Primary sort key: height in descending order.
        // 2. Secondary sort key: k value in ascending order.
        sort(people.begin(), people.end(), [](const vector<int>& a, const vector<int>& b) {
            // If heights are different, the taller person comes first.
            if (a[0] != b[0]) {
                return a[0] > b[0];
            }
            // If heights are the same, the one with smaller k comes first.
            return a[1] < b[1];
        });

        vector<vector<int>> result;
        // Iterate through the sorted people and insert them into the result vector
        // at the index specified by their k value (p[1]).
        for (const auto& p : people) {
            // result.begin() + p[1] provides an iterator to the insertion point.
            result.insert(result.begin() + p[1], p);
        }

        return result;
    }
};

Queue Reconstruction by Height in TypeScript

function reconstructQueue(people: number[][]): number[][] {
    // Sort people based on a custom comparator.
    // 1. Primary sort key: height in descending order.
    // 2. Secondary sort key: k value in ascending order.
    people.sort((a, b) => {
        if (a[0] !== b[0]) {
            // For descending order of height
            return b[0] - a[0]; 
        } else {
            // For ascending order of k
            return a[1] - b[1];
        }
    });

    const result: number[][] = [];

    // Iterate through the sorted people and insert them into the result array.
    for (const p of people) {
        // The k-value (p[1]) is the target index for insertion.
        // `splice(index, 0, element)` inserts `element` at `index`.
        // When we insert person p, all people already in `result` are taller or of equal height.
        // Thus, inserting at index p[1] correctly places them.
        result.splice(p[1], 0, p);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.