We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Queue Reconstruction by Height

Difficulty: Medium


Problem Description

You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [h_i, k_i] represents the ith person of height h_i with exactly k_i other people in front who have a height greater than or equal to h_i. 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] = [h_j, k_j] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).


Key Insights

  • Each person's position in the queue is determined by their height and the number of people taller than or equal to them in front of them.
  • Sorting the people by height in descending order allows us to place taller people first.
  • By inserting each person into their correct position based on the k_i value, we can reconstruct the queue accurately.

Space and Time Complexity

Time Complexity: O(n log n), where n is the number of people, due to sorting. Space Complexity: O(n), for the space required to store the output queue.


Solution

To solve the problem, we can use the following approach:

  1. Sort the people array by height in descending order. If two people have the same height, sort by the number of people in front in ascending order.
  2. Insert each person into the result list at the index specified by their k_i value, which indicates how many people must be in front of them who are taller or of the same height.
  3. This process ensures that the resulting queue adheres to the constraints provided.

Code Solutions

def reconstructQueue(people):
    # Sort people by height (descending) and by k (ascending)
    people.sort(key=lambda x: (-x[0], x[1]))
    queue = []
    
    # Insert each person into the queue
    for person in people:
        queue.insert(person[1], person)
    
    return queue
← Back to All Questions