MEDIUM Greedy / Sorting

406. Queue Reconstruction by Height

šŸ“– Problem

You are given an array of people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represented by the input array. 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 (queue[0] is the person at the front of the queue).

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • •Array methods (`push`, `pop`, `shift`, `slice`)
  • •Object/Map/Set usage patterns
  • •Function parameter and return typing
  • •Level-order traversal
  • •Queue discipline
  • •Shortest-step interpretation

Logical Thinking Concepts

  • •Define invariants before coding
  • •Check edge cases first (`[]`, single element, duplicates)
  • •Estimate time/space before implementation
  • •Apply BFS reasoning pattern
  • •Apply Greedy reasoning pattern

šŸ’” Approach

  • → Sort people by height descending, and by k ascending
  • → Insert each person at index k in result array
  • → This ensures there are exactly k taller/equal people in front
  • → Time: O(n²), Space: O(n)

šŸ› ļø Hints & Pitfalls

Hints

  • •Sort people by height descending, and by k ascending
  • •Insert each person at index k in result array
  • •This ensures there are exactly k taller/equal people in front

Common Pitfalls

  • •Time: O(n²), Space: O(n)

🧪 Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
reconstructQueue([[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]);
Expected:
[4, 0, 2, 1, 0, 1]
Test Case 2
Not run
Input:
reconstructQueue([[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]);
Expected:
[4, 2, 2, 0, 0, 0]
Test Case 3
Not run
Input:
reconstructQueue([[0]]);
Expected:
[null]

šŸ“ Code Editor

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit