Parcel-delivery app~25 min2s · 256 MBtarget O(n^2) time, O(n^2) spaceclassic twin: lc-427divide-and-conquer
A warehouse app stores its floor plan as a square grid. A 0 is a free cell and a 1 is a cell covered by shelving. The side is a power of two.
To save space, the app stores the plan as a quad tree. A region that is all free or all shelving is one leaf. Any other region is a node that splits into four equal quadrants.
Your team lead says: Report the size of the tree before we store it: the nodes, the leaves and the levels.
Write quad_tree_stats(grid).
grid is a list of equal rows of 0 and 1, with as many rows as columns, and the side is a power of two.Input: grid = ["0011", "0011", "1000", "1100"]
Output: [9, 7, 3]The root covers the whole 4 by 4 grid. A region splits into four quadrants unless it holds only free cells or only shelving.
| Region (row, column, size) | Blocked cells | Action |
|---|---|---|
| (0, 0, 4) | 7 | split into four |
| (0, 0, 2) | 0 | one leaf |
| (0, 2, 2) | 4 | one leaf |
| (2, 0, 2) | 3 | split into four |
| (2, 0, 1) | 1 | one leaf |
| (2, 1, 1) | 0 | one leaf |
| (3, 0, 1) | 1 | one leaf |
| (3, 1, 1) | 1 | one leaf |
| (2, 2, 2) | 0 | one leaf |
The tree has 9 nodes, 7 leaves and 3 levels.
Input: grid = ["1"]
Output: [1, 1, 1]One cell is uniform, so it is one leaf.
Input: grid = ["00000000", "00000000", "00000000", "00000000", "00000000", "00001000", "00000000", "00000000"]
Output: [13, 10, 4]The one blocked cell forces a split at every level along its path. The other quadrants of each split are free leaves.
1 ≤ grid.length ≤ 2,048, and the length is a power of twogrid.length characters, each 0 or 1A side of 2,048 means 4,194,304 cells. A scan of every region at every level reads each cell once for each level, about 11 times. With prefix sums, a region is checked in constant time, and the work is the nodes of the tree and one pass over the cells.