Queue Reconstruction by Height

medium array greedy sorting

Problem

You are given a list of people as pairs [h, k] meaning a person of height h has k taller-or-equal people in front of them. Reconstruct and return the queue as a list of [h, k] pairs.

Input[[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]]
Sort by height ↓ then k ↑; insert each at position k — shorter inserts later never violate prior k counts.

def reconstruct_queue(people):
    people.sort(key=lambda p: (-p[0], p[1]))
    out = []
    for h, k in people:
        out.insert(k, [h, k])
    return out
function reconstructQueue(people) {
  people.sort((a, b) => b[0] - a[0] || a[1] - b[1]);
  const out = [];
  for (const [h, k] of people) out.splice(k, 0, [h, k]);
  return out;
}
class Solution {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, (a, b) -> a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]);
        List<int[]> out = new LinkedList<>();
        for (int[] p : people) out.add(p[1], p);
        return out.toArray(new int[0][]);
    }
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
    sort(people.begin(), people.end(), [](auto& a, auto& b) {
        return a[0] != b[0] ? a[0] > b[0] : a[1] < b[1];
    });
    vector<vector<int>> out;
    for (auto& p : people) out.insert(out.begin() + p[1], p);
    return out;
}
Time: O(n²) Space: O(n)