Logical OR of Two Binary Grids Represented as Quad-Trees - Problem

You are given two Quad-Trees representing binary grids of size n ร— n. Your mission is to perform a logical OR operation between these two grids and return the result as a new Quad-Tree.

What is a Quad-Tree?
A Quad-Tree is a tree data structure where each internal node has exactly four children representing quadrants: topLeft, topRight, bottomLeft, and bottomRight. Each node has two properties:

  • val: True if the region contains all 1's, False if all 0's
  • isLeaf: True if this node represents a uniform region (all same values)

The Challenge:
Given quadTree1 and quadTree2, return a Quad-Tree representing the bitwise OR of the two binary matrices. The OR operation follows these rules:

  • 0 OR 0 = 0
  • 0 OR 1 = 1
  • 1 OR 0 = 1
  • 1 OR 1 = 1

Think of it as overlaying two transparent sheets - wherever there's a 1 in either sheet, the result shows a 1!

Input & Output

example_1.py โ€” Basic OR Operation
$ Input: quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,1]], quadTree2 = [[0,1],[1,1],[1,0],[1,1],[1,1]]
โ€บ Output: [[0,1],[1,1],[1,1],[1,1],[1,1]]
๐Ÿ’ก Note: Tree1 represents [[1,1],[1,0]] and Tree2 represents [[1,1],[0,1]]. The OR operation results in [[1,1],[1,1]], which is represented as a single leaf node with value True.
example_2.py โ€” Complex Structure
$ Input: quadTree1 = [[0,1],[1,0],[1,0],[1,1],[1,1]], quadTree2 = [[0,1],[1,0],[0,1],[1,1],[1,0]]
โ€บ Output: [[0,1],[1,0],[0,1],[1,1],[1,1]]
๐Ÿ’ก Note: Both trees have internal nodes with mixed values. The OR operation preserves the structure where needed and creates leaf nodes where the result is uniform.
example_3.py โ€” All Zeros vs All Ones
$ Input: quadTree1 = [[1,0]], quadTree2 = [[1,1]]
โ€บ Output: [[1,1]]
๐Ÿ’ก Note: Tree1 is all zeros (single leaf False) and Tree2 is all ones (single leaf True). OR result is all ones since True OR False = True.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Where n is the number of nodes in the larger tree, as we visit each node at most once

n
2n
โœ“ Linear Growth
Space Complexity
O(log n)

Recursion stack depth is at most logโ‚„(grid_size) for balanced quad-trees

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in both trees is in the range [1, 4h] where h is the height of the tree
  • quadTree1 and quadTree2 represent n ร— n grids
  • n == 2x where 0 โ‰ค x โ‰ค 9
  • The input trees are valid quad-trees
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen