Leetcode 406. Queue Reconstruction by Height
You are given an array of people, where people[i] = [hi, ki]
represents the ith
person having a height of hi
and exactly ki
other people in front of them who have a height greater than or equal to hi
.
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] = [hj, kj]
is the attributes of the jth
person in the queue.
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]]
To solve this problem, we’ll use a greedy approach by performing the following steps:
k
) in ascending order.k
value.people
using a custom comparator.k
value.import java.util.*;
public class Solution {
public int[][] reconstructQueue(int[][] people) {
// Sort with custom comparator
// First by height in descending and then by k value in ascending
Arrays.sort(people, (a, b) -> {
if (a[0] != b[0]) {
return b[0] - a[0];
} else {
return a[1] - b[1];
}
});
// Reconstruct the queue
List<int[]> result = new LinkedList<>();
for (int[] person : people) {
result.add(person[1], person);
}
// Convert list to array
return result.toArray(new int[people.length][2]);
}
}
So, the overall time complexity is (O(n^2)).
The approach ensures that the people are placed in the correct order, respecting both their height and the number of people in front of them, achieving the desired reconstruction of the queue.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?