You get an n × n grid of 0s and 1s, where n is a power of two. Build its quad tree and return the root. Every node has a boolean val, a boolean isLeaf, and four child pointers: topLeft, topRight, bottomLeft and bottomRight.
A block of the grid whose cells are all equal becomes a leaf: isLeaf is true, val is that value and the children are null. A mixed block becomes an inner node (isLeaf false, val may be anything) whose four children are the quad trees of its four equal quarters.
The output lists the nodes level by level as [isLeaf, val] pairs with 1 for true, and null where a child is missing.
Example 1
Input: grid = [[0,0,1,1],[0,0,1,1],[1,0,1,1],[0,1,1,1]]
Output: [[0,1],[1,0],[1,1],[0,1],[1,1],null,null,null,null,
null,null,null,null,[1,1],[1,0],[1,0],[1,1]]
Why: three quarters are uniform; bottom-left splits again2 more examples and the constraints
Example 2
Input: grid = [[1,0],[0,1]] Output: [[0,1],[1,1],[1,0],[1,0],[1,1]] Why: the cells differ, so the root has four 1 × 1 leaves
Example 3
Input: grid = [[0]] Output: [[1,0]] Why: one cell is a single leaf with value 0
Constraints
- n = grid.length = grid[i].length
- n is a power of two, 1 ≤ n ≤ 64
- Each cell is 0 or 1
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check, then splitO(n² log n)
- Build quarters, then mergeO(n²)
The idea in one sentence
Side by side
| Approach | Time | Cell reads, 64 × 64 grid | Verdict |
|---|---|---|---|
| Check, then split | O(n² log n) | Passes; rescans cells | |
| Build quarters, then merge | O(n²) | Best; each cell once |
n = side of the grid, so there are n² cells and log n levels of splitting.
Edge cases to test
- One cell. [[0]] is a single leaf with value 0; there is nothing to split.
- A uniform grid. All 1s returns one leaf, however large the grid.
- Checkerboard. No block larger than 1 × 1 is uniform, so every cell becomes its own leaf.
- Merging only leaves. Four children with the same
valmerge only if all four are leaves; an inner node'svalmeans nothing.
Common mistakes
- Merging four children that have the same
valwhen one of them is an inner node. - Mixing up the order of the quarters: it is top-left, top-right, bottom-left, bottom-right.
- Using the wrong offsets for the quarters, such as
r + sizeinstead ofr + size / 2.
How to talk through it
- 1Clarify. n is a power of two? What value should an inner node carry? In what order are the four children?
- 2Give the top-down answer. Scan the block; leaf if uniform, otherwise split into four and recurse. O(n² log n), because cells are rescanned.
- 3Flip the order. Build the quarters first. A block is uniform exactly when its four children are equal leaves.
- 4Count the work. Each cell is read once at the bottom, and there are fewer than 2n² calls in total, so O(n²).
- 5Test out loud. Run one cell, a uniform grid and a checkerboard before saying you are done.