Count Cursed Hallways - codepath/compsci_guides GitHub Wiki

TIP102 Unit 9 Session 2 Advanced (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 25-30 mins
  • 🛠️ Topics: Trees, Depth-First Search (DFS), Path Sum Calculation

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • What is the structure of the tree?
    • The tree is a binary tree where each node represents a room number in the hotel.
  • What operation needs to be performed?
    • The function needs to count the number of distinct paths in the tree where the sum of the room numbers equals a given target_sum.
  • What should be returned?
    • The function should return the total count of such paths.
HAPPY CASE
Input: 
    room_numbers = [10, 5, -3, 3, 2, None, 11, 3, -2, None, 1]
    target_sum = 8
Output: 
    3
Explanation: 
    There are 3 paths in the tree that add up to 8:
    - 5 -> 3
    - 5 -> 2 -> 1
    - -3 -> 11

EDGE CASE
Input: 
    room_numbers = [1, 2, 3]
    target_sum = 5
Output: 
    0
Explanation: 
    There are no paths in the tree that add up to 5.

2: M-atch

Match what this problem looks like to known categories of problems, e.g., Linked List or Dynamic Programming, and strategies or patterns in those categories.

For Path Sum problems, we want to consider the following approaches:

  • Depth-First Search (DFS): DFS is a natural fit for exploring all possible paths from the root to the leaves.
  • Prefix Sum with Hash Map: A hash map can be used to store the prefix sums encountered so far, which allows us to efficiently count the number of valid paths ending at each node.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea:

  • Traverse the tree using DFS, keeping track of the current path's sum. For each node, check how many times the difference between the current sum and the target_sum has been seen so far. This difference will indicate the number of valid paths ending at the current node that add up to target_sum.
1) Define a helper function `dfs(node, current_path)`:
    - Base Case: If the `node` is `None`, return 0.
    - Add the current node's value to `current_path`.
    - Initialize `path_count` to 0.
    - Traverse the `current_path` from the end to the start to check if any subpath sums up to `target_sum`.
    - Recursively call `dfs` on the left and right children of the node.
    - After the recursive calls, remove the current node's value from `current_path`.
    - Return the total `path_count`.

2) In the main function, call the helper function starting from the root node with an empty path list.
3) Return the total number of valid paths found.

⚠️ Common Mistakes

  • Forgetting to correctly manage the current_path list during recursion, leading to incorrect path sums.
  • Not properly handling edge cases like a tree with only one node or an empty tree.

4: I-mplement

Implement the code to solve the algorithm.

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

def count_cursed_hallways(hotel, target_sum):
    def dfs(node, current_path):
        if not node:
            return 0
        
        # Add the current node's value to the path
        current_path.append(node.val)
        
        # Initialize the number of valid paths ending at this node
        path_count = 0
        current_sum = 0
        
        # Check the sums of all paths ending at this node
        for i in range(len(current_path) - 1, -1, -1):
            current_sum += current_path[i]
            if current_sum == target_sum:
                path_count += 1
        
        # Continue DFS on left and right subtrees
        path_count += dfs(node.left, current_path)
        path_count += dfs(node.right, current_path)
        
        # Remove the current node's value from the path before returning
        current_path.pop()
        
        return path_count
    
    return dfs(hotel, [])

# Example Usage:
room_numbers = [10, 5, -3, 3, 2, None, 11, 3, -2, None, 1]
hotel = build_tree(room_numbers)
print(count_cursed_hallways(hotel, 8))  # Output: 3

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

- Example 1:
    - Input: 
        `room_numbers = [10, 5, -3, 3, 2, None, 11, 3, -2, None, 1]`
        `target_sum = 8`
    - Execution: 
        - Traverse the tree using DFS.
        - Check for paths that sum to 8 at each node.
    - Output: 
        3
- Example 2:
    - Input: 
        `room_numbers = [1, 2, 3]`
        `target_sum = 5`
    - Execution: 
        - Traverse the tree using DFS.
        - No paths sum to 5.
    - Output: 
        0

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Time Complexity:

  • Time Complexity: O(N^2) in the worst case for an unbalanced tree, where N is the number of nodes in the tree.
    • Explanation: The DFS traversal checks all possible paths at each node, leading to a quadratic time complexity in the worst-case scenario of an unbalanced tree.

Space Complexity:

  • Space Complexity: O(N) where N is the number of nodes in the tree.
    • Explanation: The space complexity is due to the recursion stack and the current_path list, which can grow up to N in the worst case for a skewed tree.