Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: House Robber III

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "337" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police. Example 1: Input: root = [3,2,3,null,3,null,1] Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: Input: root = [3,4,5,1,3,null,1] Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9. Constraints: The number of nodes in the tree is in the range [1, 104]. 0 <= Node.val <= 104

Explanation

Here's the breakdown of the solution:

  • Dynamic Programming: The core idea is to use dynamic programming to avoid recomputation. For each node, we calculate two values: the maximum loot including the node and the maximum loot excluding the node.

  • Recursive Post-order Traversal: A recursive post-order traversal is used to visit the nodes in a bottom-up manner. This ensures that when we process a node, the results for its children are already available.

  • Memoization: Although not explicitly using a memoization table, the function rob_helper effectively achieves memoization by returning a tuple containing the two computed values (including and excluding the node). This avoids recalculating the same subproblems.

  • Time Complexity: O(N), where N is the number of nodes in the tree. Each node is visited exactly once.

  • Space Complexity: O(H), where H is the height of the tree, due to the recursion stack. In the worst case (skewed tree), H can be equal to N. In the best case (balanced tree), H is log(N).

Code

    class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def rob(root):
    """
    Calculates the maximum amount of money the thief can rob without alerting the police.

    Args:
        root: The root of the binary tree representing the houses.

    Returns:
        The maximum amount of money the thief can rob.
    """

    def rob_helper(node):
        """
        Helper function to recursively calculate the maximum loot.

        Returns a tuple: (max_loot_including_node, max_loot_excluding_node)
        """
        if not node:
            return 0, 0

        left_include, left_exclude = rob_helper(node.left)
        right_include, right_exclude = rob_helper(node.right)

        # If we include the current node, we cannot include its children.
        include_current = node.val + left_exclude + right_exclude

        # If we exclude the current node, we can choose to include or exclude its children,
        # whichever gives the maximum loot.
        exclude_current = max(left_include, left_exclude) + max(right_include, right_exclude)

        return include_current, exclude_current

    include_root, exclude_root = rob_helper(root)
    return max(include_root, exclude_root)

More from this blog

C

Chatmagic blog

2894 posts