KatInterview

773. Logical OR of Two Binary Grids Represented as Quad-Trees

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to compute the logical OR of two binary matrices and represent the result as a Quad-Tree. We are given two Quad-Trees, quadTree1 and quadTree2, each representing an n x n binary matrix. The task is to construct a third Quad-Tree for the matrix resulting from the bitwise OR operation on the corresponding cells of the two input matrices.

Solution

Logical OR of Two Binary Grids Represented as Quad-Trees in Python

"""
# Definition for a QuadTree node.
class Node:
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
"""

class Solution:
    def intersect(self, quadTree1: 'Node', quadTree2: 'Node') -> 'Node':
        # If quadTree1 is a leaf node.
        if quadTree1.isLeaf:
            # If its value is True, the OR result is always a grid of 1s.
            # So return quadTree1 itself. If its value is False, the OR
            # result is identical to quadTree2's grid.
            return quadTree1 if quadTree1.val else quadTree2

        # If quadTree2 is a leaf node (and quadTree1 is not).
        if quadTree2.isLeaf:
            # Symmetrically, if quadTree2's value is True, result is a grid of 1s.
            # If False, the result is identical to quadTree1's grid.
            return quadTree2 if quadTree2.val else quadTree1
        
        # If both are internal nodes, recursively find the intersection of children.
        tl = self.intersect(quadTree1.topLeft, quadTree2.topLeft)
        tr = self.intersect(quadTree1.topRight, quadTree2.topRight)
        bl = self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft)
        br = self.intersect(quadTree1.bottomRight, quadTree2.bottomRight)
        
        children = [tl, tr, bl, br]
        
        # Check if all children are leaf nodes and have the same value.
        # If so, they can be merged into a single leaf node.
        if all(c.isLeaf for c in children) and len(set(c.val for c in children)) == 1:
            return Node(tl.val, True, None, None, None, None)
        else:
            # Otherwise, create a new internal node.
            # The value of an internal node is arbitrary; False or 0 is fine.
            return Node(False, False, tl, tr, bl, br)

Logical OR of Two Binary Grids Represented as Quad-Trees in Java

/*
// Definition for a QuadTree node.
class Node {
    public boolean val;
    public boolean isLeaf;
    public Node topLeft;
    public Node topRight;
    public Node bottomLeft;
    public Node bottomRight;

    public Node() {}

    public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = _topLeft;
        topRight = _topRight;
        bottomLeft = _bottomLeft;
        bottomRight = _bottomRight;
    }
};
*/

class Solution {
    public Node intersect(Node quadTree1, Node quadTree2) {
        // If quadTree1 is a leaf node.
        if (quadTree1.isLeaf) {
            // If val is true, OR result is always true. Return a node representing all true.
            // If val is false, OR result is determined by quadTree2.
            return quadTree1.val ? quadTree1 : quadTree2;
        }

        // If quadTree2 is a leaf node (and quadTree1 is not).
        if (quadTree2.isLeaf) {
            // Symmetrically, if quadTree2.val is true, result is true.
            // If false, result is determined by quadTree1.
            return quadTree2.val ? quadTree2 : quadTree1;
        }

        // If both are internal nodes, recurse on children.
        Node tl = intersect(quadTree1.topLeft, quadTree2.topLeft);
        Node tr = intersect(quadTree1.topRight, quadTree2.topRight);
        Node bl = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft);
        Node br = intersect(quadTree1.bottomRight, quadTree2.bottomRight);

        // Check for merge condition: all children are leaves with same value.
        if (tl.isLeaf && tr.isLeaf && bl.isLeaf && br.isLeaf &&
            tl.val == tr.val && tl.val == bl.val && tl.val == br.val) {
            // Return a new merged leaf node.
            return new Node(tl.val, true, null, null, null, null);
        } else {
            // Return a new internal node with the computed children.
            // val can be anything for an internal node.
            return new Node(false, false, tl, tr, bl, br);
        }
    }
}

Logical OR of Two Binary Grids Represented as Quad-Trees in C++

/*
// Definition for a QuadTree node.
class Node {
public:
    bool val;
    bool isLeaf;
    Node* topLeft;
    Node* topRight;
    Node* bottomLeft;
    Node* bottomRight;
    
    Node() {
        val = false;
        isLeaf = false;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    Node(bool _val, bool _isLeaf) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = _topLeft;
        topRight = _topRight;
        bottomLeft = _bottomLeft;
        bottomRight = _bottomRight;
    }
};
*/

class Solution {
public:
    Node* intersect(Node* quadTree1, Node* quadTree2) {
        // If quadTree1 is a leaf node.
        if (quadTree1->isLeaf) {
            // If its value is true (1), the OR result is always 1. So, return quadTree1.
            // If its value is false (0), the OR result is determined by quadTree2. So, return quadTree2.
            return quadTree1->val ? quadTree1 : quadTree2;
        }
        
        // If quadTree2 is a leaf node (and quadTree1 is not).
        if (quadTree2->isLeaf) {
            // Similar logic: if quadTree2 has value 1, result is 1.
            // If it has value 0, result is quadTree1.
            return quadTree2->val ? quadTree2 : quadTree1;
        }
        
        // If both are internal nodes, recursively call intersect for their children.
        Node* tl = intersect(quadTree1->topLeft, quadTree2->topLeft);
        Node* tr = intersect(quadTree1->topRight, quadTree2->topRight);
        Node* bl = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft);
        Node* br = intersect(quadTree1->bottomRight, quadTree2->bottomRight);
        
        // Check if all children are leaf nodes and have the same value.
        // If so, they can be merged into a single leaf node.
        if (tl->isLeaf && tr->isLeaf && bl->isLeaf && br->isLeaf &&
            tl->val == tr->val && tr->val == bl->val && bl->val == br->val) {
            // Create a new leaf node with the common value.
            return new Node(tl->val, true);
        }
        
        // If children cannot be merged, create a new internal node.
        // The value of an internal node is arbitrary, we can use false.
        return new Node(false, false, tl, tr, bl, br);
    }
};

Logical OR of Two Binary Grids Represented as Quad-Trees in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: boolean
 *     isLeaf: boolean
 *     topLeft: _Node | null
 * 	topRight: _Node | null
 * 	bottomLeft: _Node | null
 * 	bottomRight: _Node | null
 * 	constructor(val?: boolean, isLeaf?: boolean, topLeft?: _Node, topRight?: _Node, bottomLeft?: _Node, bottomRight?: _Node) {
 *         this.val = (val===undefined ? false : val)
 *         this.isLeaf = (isLeaf===undefined ? false : isLeaf)
 *         this.topLeft = (topLeft===undefined ? null : topLeft)
 *         this.topRight = (topRight===undefined ? null : topRight)
 *         this.bottomLeft = (bottomLeft===undefined ? null : bottomLeft)
 *         this.bottomRight = (bottomRight===undefined ? null : bottomRight)
 *   }
 * }
 */


function intersect(quadTree1: _Node | null, quadTree2: _Node | null): _Node | null {
    // Although problem constraints suggest non-null roots, we handle null inputs for robustness.
    // A null tree can be seen as a grid of zeros; ORing with it returns the other tree.
    if (!quadTree1) return quadTree2;
    if (!quadTree2) return quadTree1;
    
    // If quadTree1 is a leaf node.
    if (quadTree1.isLeaf) {
        // If its value is true, the OR result is always a grid of 1s.
        // If its value is false, the OR result is determined by quadTree2.
        return quadTree1.val ? quadTree1 : quadTree2;
    }

    // If quadTree2 is a leaf node (and quadTree1 is not).
    if (quadTree2.isLeaf) {
        // Symmetrically, if quadTree2's value is true, result is a grid of 1s.
        // If false, result is determined by quadTree1.
        return quadTree2.val ? quadTree2 : quadTree1;
    }

    // If both are internal nodes, recursively call intersect on their children.
    const topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft);
    const topRight = intersect(quadTree1.topRight, quadTree2.topRight);
    const bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft);
    const bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight);

    // Check if all children are leaf nodes and have the same value.
    if (topLeft?.isLeaf && topRight?.isLeaf && bottomLeft?.isLeaf && bottomRight?.isLeaf &&
        topLeft.val === topRight.val && topRight.val === bottomLeft.val && bottomLeft.val === bottomRight.val) {
        // If so, merge them into a single leaf node.
        return new _Node(topLeft.val, true);
    } else {
        // Otherwise, create a new internal node.
        // The value for an internal node is arbitrary.
        return new _Node(false, false, topLeft, topRight, bottomLeft, bottomRight);
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.