Skip to content
Decoder

Construct Quad Tree

Medium

Problem

A quad tree stores a square grid of 0s and 1s. If every cell in the grid has the same value, the tree is a single leaf holding that value. Otherwise the grid is cut into four equal quarters, and each quarter becomes its own quad tree, in this order: top-left, top-right, bottom-left, bottom-right.

Given an n x n grid, build its quad tree and return it in this form: a leaf is the number 0 or 1, and any other node is a list of its four children in the order above.

Example 1

[[1, 1],

Example 2

Input
[1, 1]]
Output
1

Example 3

[[0, 0],

Example 4

Input
[1, 0]]
Output
[0, 0, 1, 0]

Example 5

[[1, 1, 0, 0],

Example 6

 [1, 1, 0, 0],

Example 7

 [1, 1, 1, 1],

Example 8

Input
[1, 1, 1, 0]]
Output
[1, 0, 1, [1, 1, 1, 0]]

Constraints

  • n == grid.length == grid[i].length
  • n is a power of two: n = 2^x with 0 <= x <= 6
  • grid[i][j] is 0 or 1.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.