#406

Queue Reconstruction by Height

Medium
ArrayBinary Indexed TreeSegment TreeSorting
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach involves trying to place each person in the queue one by one, checking how many taller people are in front of them. This is straightforward but inefficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the people array by height in descending order and by k in ascending order for those with the same height.
  2. 2Step 2: Initialize an empty queue.
  3. 3Step 3: For each person in the sorted list, insert them into the queue at the index equal to their k value.
solution.py8 lines
1# Full working Python code
2people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
3
4people.sort(key=lambda x: (-x[0], x[1]))
5queue = []
6for person in people:
7    queue.insert(person[1], person)
8print(queue)

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.