Skip to content

Commit f3cb9d3

Browse files
author
Joseph Luce
authored
Create 406_queue_reconstruction_by_height.md
1 parent 284edcc commit f3cb9d3

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# 406. Queue Reconstruction by Height
2+
3+
## Best Solution
4+
- Runtime: O(Nlog(N))
5+
- Space: O(1) (Assuming the result isn't extra space)
6+
- N = Number of elements in array
7+
8+
There will be two sorts involved. One sorts the array by height, followed by an insertion sort by index.
9+
10+
1. Sort the people by their height, highest to shortest, if heights are same, sort by index, smallest to largest.
11+
2. Starting with the highest people, insert them into the result via. their indexes.
12+
13+
The logic behind this is by starting with the highest people, we guarantee that the next element inserted via. their index, will be inserted in the correct slot compared to their counter parts in respect to their index.
14+
```
15+
Try inserting: [[7,0], [6,0], [5,0]] -> [[5,0], [6,0], [7,0]]
16+
Then try: [[7,0], [6,0], [5,0], [4,1]] -> [[5,0], [4,1], [6,0], [7,0]]
17+
```
18+
19+
```
20+
Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
21+
22+
Sorted: [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
23+
24+
Insertion:
25+
1. [[7,0]]
26+
2. [[7,0], [7,1]]
27+
3. [[7,0], [6,1], [7,1]]
28+
4. [[5,0], [7,0], [6,1], [7,1]]
29+
5. [[5,0], [7,0], [5,2], [6,1], [7,1]]
30+
6. [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
31+
```
32+
33+
The first sort is O(Nlog(N)) while the second sort is O(N) due to known indexes for insertion.
34+
35+
```
36+
class Solution:
37+
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
38+
people.sort(key=lambda x: (x[0], -x[1]), reverse=True)
39+
result = list()
40+
for p in people:
41+
if p[1] >= len(result):
42+
result.insert(len(result), p)
43+
else:
44+
result.insert(p[1], p)
45+
return result
46+
```

0 commit comments

Comments
 (0)