Path Sum III (Prefix Sum)

beginner
11 min

Path Sum III (Prefix Sum)

Welcome to a comprehensive guide on Path Sum III (Prefix Sum)! In this lesson, we'll dive into the world of Data Structures and Algorithms, focusing on a problem-solving approach known as Prefix Sum.

🎯 Why Prefix Sum? Prefix Sum is a useful technique for solving problems related to array manipulation. It allows us to calculate the sum of elements in an array from a given index to the end or from the start to a given index in constant time. This can significantly speed up our code, making it more efficient for handling large datasets.

Understanding Prefix Sum

Let's start with a simple example to illustrate the concept.

python
nums = [1, 2, 3, 4, 5] prefix_sum = [0] + nums # Adding 0 as the first element to make the prefix sum possible from index 0 for i in range(1, len(nums)): prefix_sum[i] += prefix_sum[i - 1] print(prefix_sum) # Output: [0, 1, 3, 6, 10, 15]

In the above example, we've created a prefix sum array by calculating the sum of elements from the start to the current index for each element in the original array.

📝 Note: Adding 0 as the first element is crucial to ensure we can calculate the prefix sum for index 0.

Path Sum III

Now that we've grasped the basics of Prefix Sum, let's apply it to solve the Path Sum III problem.

Problem Statement:

Given a binary tree and an integer targetSum, find all paths where the sum of the node values in the path equals targetSum.

Here's a step-by-step approach to solve Path Sum III using Prefix Sum:

  1. Calculate the prefix sum of the tree's node values using Depth-First Search (DFS).
  2. For each node, subtract the prefix sum of the left subtree and the prefix sum of the right subtree from the current node's prefix sum.
  3. Check if the resulting difference equals the targetSum minus the current node's value.
  4. If it does, add the current path to the result.

Code Example:

python
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def prefix_sum_tree(root): if not root: return 0 prefix_sum = [0] stack = [(root, 0)] while stack: node, current_sum = stack.pop() prefix_sum.append(prefix_sum[-1] + current_sum + node.val) stack.append((node.left, prefix_sum[-1])) stack.append((node.right, prefix_sum[-1])) return prefix_sum def path_sum(root, targetSum): prefix_sum = prefix_sum_tree(root) def dfs(node, current_sum, targetSum): if not node: return current_sum += prefix_sum[node.val] if not node.left and not node.right and current_sum == targetSum: result.append([node.val]) return if node.left: dfs(node.left, current_sum - prefix_sum[node.left.val], targetSum) if node.right: dfs(node.right, current_sum - prefix_sum[node.right.val], targetSum) result = [] dfs(root, 0, targetSum) return result # Example usage root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) paths = path_sum(root, 7) print(paths) # Output: [[2, 4, 3], [2, 2, 3]]

💡 Pro Tip: Using Prefix Sum can greatly improve the performance of many algorithmic problems. Keep exploring different problems and practice implementing Prefix Sum to strengthen your problem-solving skills!