406. Queue Reconstruction by Height
Problem
People in a queue were shuffled; people[i] = [h, k] says person i has height h and exactly k people in front of them are at least as tall. Reconstruct and return the queue.
Example: [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] → [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
Constraints: up to 2000 people.
Sort by height descending, then k ascending. Insert each person at index k: everyone already placed is taller or equal, so exactly k of them are in front, and shorter people inserted later don't affect it.
sorted: [7,0] [7,1] [6,1] [5,0] [5,2] [4,4]
insert: [7,0]
[7,0] [7,1]
[7,0] [6,1] [7,1]
[5,0] [7,0] [6,1] [7,1]
[5,0] [7,0] [5,2] [6,1] [7,1]
[5,0] [7,0] [5,2] [6,1] [4,4] [7,1]
Complexity: O(n²).
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
res = []
for h, k in sorted(people, key=lambda p: (-p[0], p[1])):
res.insert(k, [h, k])
return res
P = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
assert Solution().reconstructQueue(P) == [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
assert Solution().reconstructQueue([[6, 0], [5, 0], [4, 0], [3, 2], [2, 2], [1, 4]]) == [[4, 0], [5, 0], [2, 2], [3, 2], [1, 4], [6, 0]]
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[]> res = new ArrayList<>();
for (int[] p : people) res.add(p[1], p);
return res.toArray(new int[0][]);
}
}
func reconstructQueue(people [][]int) [][]int {
sort.Slice(people, func(i, j int) bool { // tallest first; fewer people in front first
a, b := people[i], people[j]
return a[0] > b[0] || a[0] == b[0] && a[1] < b[1]
})
res := [][]int{}
for _, p := range people { // everyone already placed is at least as tall: insert at index k
k := p[1]
res = append(res, p) // grow by one, then shift right from k
copy(res[k+1:], res[k:])
res[k] = p
}
return res
}