Social feed~25 min2s · 256 MBtarget O(n^2) time, O(n) spaceclassic twin: lc-406sorting
A social app lets friends line up for a group photo. The app lost the order. Each person still knows two numbers: their height, and how many people in front of them are at least as tall. Heights can repeat, and exactly one line fits all the numbers.
Write rebuild_the_line(people).
people[i] = [height, k], where k is the number of people in front of person i with a height of at least height.[height, k] pairs in line order. Exactly one line fits.Input: people = [[150, 1], [160, 0], [150, 3], [170, 1], [170, 0], [165, 1]]
Output: [[160, 0], [150, 1], [170, 0], [150, 3], [165, 1], [170, 1]]Handle the tallest people first, and for equal heights the smaller k first. Insert each person at place k of the line built so far.
| Person [height, k] | Insert at place | Line after the insert |
|---|---|---|
| [170, 0] | 0 | 170 |
| [170, 1] | 1 | 170, 170 |
| [165, 1] | 1 | 170, 165, 170 |
| [160, 0] | 0 | 160, 170, 165, 170 |
| [150, 1] | 1 | 160, 150, 170, 165, 170 |
| [150, 3] | 3 | 160, 150, 170, 150, 165, 170 |
The final line is [[160, 0], [150, 1], [170, 0], [150, 3], [165, 1], [170, 1]].
Input: people = [[170, 0], [170, 1], [170, 2]]
Output: [[170, 0], [170, 1], [170, 2]]All have the same height, so each counts everyone in front. The line is [[170, 0], [170, 1], [170, 2]].
Input: people = [[150, 2], [160, 1], [170, 0]]
Output: [[170, 0], [160, 1], [150, 2]]The tallest stands first and the shortest last: [[170, 0], [160, 1], [150, 2]].
0 ≤ people.length ≤ 20,000 (friends in one photo)0 ≤ height ≤ 1,000,0000 ≤ k < people.lengthEach insert moves the people behind it, so n inserts cost about n × n small moves. At n = 20,000 that is a few hundred million cheap moves, which fits easily. A tree can do it in n log n for larger lists.