Maps app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-958bfs
A maps app draws a city in regions. Each region is split into at most two smaller regions, a west one and an east one. So the regions form a tree, with the whole city at the top.
To save memory on phones, your team lead wants to store the tree in a plain array, the way a heap is stored. The whole city goes in cell 0. The two parts of the region in cell p go in cells 2p + 1 and 2p + 2. That only saves memory when no cell is left empty.
Write packs_without_gaps(left, right).
0 to n - 1, and region 0 is the whole city. An empty map has two empty lists.left[i] and right[i] are the numbers of the west and east parts of region i, or -1 where there is none.0 goes in cell 0. If a region is in cell p, its west part goes in cell 2p + 1 and its east part in cell 2p + 2.true when the n regions fill exactly the cells 0 to n - 1, with no empty cell between them. Return false otherwise. An empty map gives true.Input: left = [1, 3, 5, -1, -1, -1], right = [2, 4, -1, -1, -1, -1]
Output: trueRegion 0 has the parts 1 and 2. Region 1 has the parts 3 and 4. Region 2 has only a west part, 5.
Read the cells in level order, the empty ones too. That is the order of the array: every region adds its west cell and then its east cell at the back of a queue.
| Cell | What is in it | An empty cell seen before? | Cells added at the back |
|---|---|---|---|
| 0 | region 0 |
no | region 1, region 2 |
| 1 | region 1 |
no | region 3, region 4 |
| 2 | region 2 |
no | region 5, empty |
| 3 | region 3 |
no | empty, empty |
| 4 | region 4 |
no | empty, empty |
| 5 | region 5 |
no | empty, empty |
| 6 | empty | this is the first one | nothing |
| 7 to 12 | empty | yes, and no region follows | nothing |
Every region came before the first empty cell, so the six regions fill cells 0 to 5. The answer is true.
Input: left = [1, -1, -1, -1], right = [2, 3, -1, -1]
Output: falseRegion 1, in cell 1, has only an east part. Cell 3 stays empty, and region 3 lands in cell 4.
Input: left = [], right = []
Output: true0 ≤ length of left = length of right ≤ 10^5left and right is -1 or a region number from 1 to n - 10A map can be a chain 100,000 levels deep. Drawing every level with a slot for each possible region doubles the slots at every level, so it breaks after about 25 levels. The cell numbers of a chain double too, and pass 2^64 after 64 levels.
Read the cells in level order with a queue, and stop at the first region that comes after an empty cell. Every region is looked at once, and no number grows.