Problem Description
Given an array of people where each person is represented as [h, k] (h is the person's height and k is the number of people in front of this person who have a height greater than or equal to h), reconstruct the queue.
Key Insights
- Sort the array in descending order by height; for people with equal height, sort in ascending order by k.
- When inserting a person into the result list, their k value indicates the index at which they should be placed.
- This greedy approach guarantees that each person is inserted after all taller or equal height persons have already been placed.
Space and Time Complexity
Time Complexity: O(n^2) in the worst case due to the insertion process in the list. Space Complexity: O(n) for storing the output queue.
Solution
The solution leverages a greedy algorithm. First, sort the input array such that taller people come first and, for the same height, the person with a smaller k comes first. By doing this, when you iterate over the sorted list and insert each person at the index equal to their k value, the relative order of people already inserted (who are taller or of the same height) remains valid, fulfilling the condition of exactly k people in front who are taller or equal.