Engineering platform~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-987bfs
You work on the engineering platform behind an app's page builder. A page layout is a tree of blocks. Each block has an id and at most two blocks inside it.
A block inside on the left is placed one column to the left and one row down. A block inside on the right is placed one column to the right and one row down.
The accessibility team wants the blocks read column by column, from the leftmost column to the rightmost, and from the top of each column to the bottom.
Write blocks_by_column(values, left, right).
0 to n - 1, and block 0 is the top, at column 0 and row 0. An empty layout has three empty lists.values[i] is the id of block i. left[i] and right[i] are the numbers of the blocks inside it, or -1 where there is none.Input: values = [8, 3, 10, 1, 6, 14, 4, 7, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
Output: [[1], [3, 4], [8, 6], [10, 7, 13], [14]]Block 0 (id 8) holds 1 (id 3) and 2 (id 10). Block 1 holds 3 (id 1) and 4 (id 6). Block 2 has only a right block 5 (id 14).
Block 4 holds 6 (id 4) and 7 (id 7). Block 5 has only a left block 8 (id 13).
Find each block's column and row with a level-by-level walk. Then sort by column, then row, then id.
| Block (id) | Column | Row |
|---|---|---|
0 (8) |
0 | 0 |
1 (3) |
-1 | 1 |
2 (10) |
1 | 1 |
3 (1) |
-2 | 2 |
4 (6) |
0 | 2 |
5 (14) |
2 | 2 |
6 (4) |
-1 | 3 |
7 (7) |
1 | 3 |
8 (13) |
1 | 3 |
Column 1 holds the ids 10 (row 1), then 7 and 13 (both row 3). They share a row, so the smaller id, 7, comes first.
Input: values = [5, 3, 7, 9, 4], left = [1, -1, 4, -1, -1], right = [2, 3, -1, -1, -1]
Output: [[3], [5, 4, 9], [7]]Block 0 has 1 on the left (id 3) and 2 on the right (id 7). Block 1 has a right block 3 (id 9), and block 2 has a left block 4 (id 4). Both land in column 0, row 2, so the smaller id, 4, comes before 9.
Input: values = [], left = [], right = []
Output: []0 ≤ length of values = length of left = length of right ≤ 10^50 ≤ values[i] ≤ 10^6left and right is -1 or a block number from 1 to n - 10A layout can be a chain going right, which has 100,000 columns. Scanning every block for every column costs about n^2 steps on it.
Give each block a column and a row in one walk, and sort all the blocks once. A sort of 100,000 blocks costs about 1.7 million comparisons.