#558
Logical OR of Two Binary Grids Represented as Quad-Trees
MediumDivide and ConquerTreeDivide and ConquerTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n²) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal solution leverages the properties of quad-trees to directly combine nodes without converting to matrices. This approach avoids unnecessary space and time complexity by working directly with the quad-tree structure.
⚙️
Algorithm
3 steps- 1Step 1: If either node is a leaf, return the non-leaf node or the leaf node with the value True.
- 2Step 2: If both nodes are leaves, return a new leaf node with value True if either node is True.
- 3Step 3: If both nodes are not leaves, recursively combine their four children using logical OR.
solution.py23 lines
1# Full working Python code
2class Node:
3 def __init__(self, val=False, isLeaf=False):
4 self.val = val
5 self.isLeaf = isLeaf
6 self.topLeft = None
7 self.topRight = None
8 self.bottomLeft = None
9 self.bottomRight = None
10
11
12def logical_or_quad_trees(qt1, qt2):
13 if qt1.isLeaf:
14 return Node(True, True) if qt1.val else qt2
15 if qt2.isLeaf:
16 return Node(True, True) if qt2.val else qt1
17 new_node = Node(False, False)
18 new_node.topLeft = logical_or_quad_trees(qt1.topLeft, qt2.topLeft)
19 new_node.topRight = logical_or_quad_trees(qt1.topRight, qt2.topRight)
20 new_node.bottomLeft = logical_or_quad_trees(qt1.bottomLeft, qt2.bottomLeft)
21 new_node.bottomRight = logical_or_quad_trees(qt1.bottomRight, qt2.bottomRight)
22 return new_node
23ℹ
Complexity note: This complexity is linear in terms of the number of nodes in the quad-trees, as we only traverse each node once. Space complexity is O(h) due to the recursion stack.
- 1Understanding the structure of quad-trees is crucial for optimizing the solution.
- 2Directly manipulating quad-tree nodes can save time and space compared to converting to matrices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.