Queue Reconstruction by Height

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are given an array of people, where people[i] = [h_i, k_i] represents the height h_i of the i-th person and k_i is the number of people in front of this person who have a height greater than or equal to h_i.

Reconstruct and return the queue so that each person is placed at a position consistent with their k_i value.

Examples

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

Explanation: Person [5,0] has no one taller or equal in front. Person [7,0] also has no one taller in front. Person [5,2] has two people ([7,0] and [5,0] counted as >= 5) in front. And so on for each person.

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

Explanation: After sorting and inserting by the greedy strategy, every person's k value matches the count of people in front with height >= theirs.

Example 3:

Input: people = [[9,0],[7,0]]

Output: [[7,0],[9,0]]

Explanation: Both have k = 0. Sorting by height descending places [9,0] first, then [7,0] is inserted at index 0, pushing [9,0] to index 1. Result: [[7,0],[9,0]].

Constraints

  • 1 <= people.length <= 2000
  • 0 <= h_i <= 10^6
  • 0 <= k_i < people.length
  • It is guaranteed that the queue can be reconstructed
Source: Greedy Techniques pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle