- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 35 lines of Python from the credited upstream file logical-or-of-two-binary-grids-represented-as-quad-trees.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Node(object):5 def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):6 self.val = val7 self.isLeaf = isLeaf8 self.topLeft = topLeft9 self.topRight = topRight10 self.bottomLeft = bottomLeft11 self.bottomRight = bottomRight12 13 14class Solution(object):15 def intersect(self, quadTree1, quadTree2):16 """17 :type quadTree1: Node18 :type quadTree2: Node19 :rtype: Node20 """21 if quadTree1.isLeaf:22 return quadTree1 if quadTree1.val else quadTree223 elif quadTree2.isLeaf:24 return quadTree2 if quadTree2.val else quadTree125 topLeftNode = self.intersect(quadTree1.topLeft, quadTree2.topLeft)26 topRightNode = self.intersect(quadTree1.topRight, quadTree2.topRight)27 bottomLeftNode = self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft)28 bottomRightNode = self.intersect(quadTree1.bottomRight, quadTree2.bottomRight)29 if topLeftNode.isLeaf and topRightNode.isLeaf and \30 bottomLeftNode.isLeaf and bottomRightNode.isLeaf and \31 topLeftNode.val == topRightNode.val == bottomLeftNode.val == bottomRightNode.val:32 return Node(topLeftNode.val, True, None, None, None, None)33 return Node(True, False, topLeftNode, topRightNode, bottomLeftNode, bottomRightNode)34 35