People stood in a line, but the line has been shuffled. Each person is given as [h, k]: h is their height and k is how many people in front of them in the original line were at least as tall as they are.
Rebuild the original line from the list people and return it, front of the line first. The input always describes some real line, and that line is unique.
Example 1
Input: people = [[3,1],[6,0],[2,2],[6,1],[5,0]] Output: [[5,0],[3,1],[2,2],[6,0],[6,1]] Why: [2,2] has 5 and 3 ahead; [6,1] has the other 6 ahead
2 more examples and the constraints
Example 2
Input: people = [[4,2],[4,0],[4,1]] Output: [[4,0],[4,1],[4,2]] Why: equal heights count, so k is just the position
Example 3
Input: people = [[9,0]] Output: [[9,0]] Why: one person, nobody in front
Constraints
- 1 ≤ number of people ≤ 2,000
- 0 ≤ h ≤ 1,000,000
- 0 ≤ k < number of people
- A valid line always exists
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Shortest first, count empty seatsO(n²)
- Tallest first, insert at kO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 people | Verdict |
|---|---|---|---|
| Shortest first, count empty seats | O(n²) | Passes; scans seats one by one | |
| Tallest first, insert at k | O(n²) | Best; one insert per person |
n = number of people. Both are quadratic; the inserts are fast block moves, the seat scan is a loop with checks.
Edge cases to test
- Equal heights. [[4,2],[4,0],[4,1]]: people of the same height count each other, so the answer is ordered by k.
- One person. [[9,0]] is already the line.
- Height 0. Heights can be 0; a 0 still counts other 0s in front of it.
- Everyone counted. [[1,3],[2,2],[3,1],[4,0]] puts the tallest first and the shortest last.
Common mistakes
- Sorting equal heights by k descending in the tallest-first method, so [6,1] is inserted before [6,0] exists.
- Counting only strictly taller people, when equal heights count too.
- Inserting by height order but appending instead of inserting at index k.
How to talk through it
- 1Clarify. Does k count equal heights? Is a valid line always possible? Is the answer unique?
- 2Find what is easy to place. A person's k ignores shorter people, so the tallest people can be placed without knowing anyone else.
- 3State the greedy. Sort tallest first, ties by k ascending, then insert each at index k. Later inserts are shorter, so they never break earlier counts.
- 4Give the cost. O(n log n) to sort and O(n²) for the inserts; fine for 2,000 people.
- 5Test out loud. Run all equal heights, a single person, and Example 1 step by step.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?