Bird
Raised Fist0

The following code attempts to count the number of paths summing to targetSum using iterative DFS and prefix sums. Which line contains a subtle bug that causes incorrect path counts?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Path Sum III (Any Path)
The following code attempts to count the number of paths summing to targetSum using iterative DFS and prefix sums. Which line contains a subtle bug that causes incorrect path counts?
class Solution:
    def pathSum(self, root, targetSum):
        if not root:
            return 0
        prefix_counts = {0: 1}
        result = 0
        stack = [(root, 0, False)]  # node, current_sum, visited_children

        while stack:
            node, current_sum, visited = stack.pop()
            if node is None:
                continue
            if not visited:
                current_sum += node.val
                result += prefix_counts.get(current_sum - targetSum, 0)
                prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1
                stack.append((node, current_sum, True))  # Mark node as visited
                stack.append((node.right, current_sum, False))
                stack.append((node.left, current_sum, False))
            else:
                # BUG: Missing decrement of prefix_counts on backtrack
                # prefix_counts[current_sum] -= 1
                pass

        return result
ALine where prefix_counts[current_sum] should be decremented but is missing
BLine where prefix_counts[current_sum] is incremented
CLine where current_sum is incremented by node.val
DLine where stack appends left and right children
Step-by-Step Solution
Solution:
  1. Step 1: Identify prefix_counts usage

    prefix_counts tracks how many times a prefix sum has occurred along the current path.
  2. Step 2: Recognize missing decrement on backtrack

    Failing to decrement prefix_counts[current_sum] when backtracking causes counts to accumulate incorrectly across branches.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing decrement leads to overcounting paths [OK]
Quick Trick: Always decrement prefix_counts on backtrack [OK]
Common Mistakes:
MISTAKES
  • Not decrementing prefix_counts after visiting children
  • Assuming prefix_counts only grows
  • Confusing when to mark node as visited
Trap Explanation:
PITFALL
  • The missing decrement is subtle because code runs without error but counts paths incorrectly.
Interviewer Note:
CONTEXT
  • Tests if candidate understands prefix sum bookkeeping and backtracking in DFS.
Master "Path Sum III (Any Path)" in Tree: Depth-First Search

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Tree: Depth-First Search Quizzes