Bird
Raised Fist0
Interview Prepchallenge-problemshardFacebookAmazonGoogleMicrosoft

Binary Tree Maximum Path Sum

Choose your preparation mode4 modes available
▶
Steps
setup

Start at Root Node

We begin the recursion at the root node with value 1. The global max_sum is initialized to negative infinity.

💡 Initializing max_sum to -inf ensures any path sum will update it.
Line:def maxPathSum(root): max_sum = float('-inf') def helper(node):
💡 The algorithm starts with the root and prepares to explore all paths.
📊
Binary Tree Maximum Path Sum - Watch the Algorithm Execute, Step by Step
Watching the recursion unfold and how the algorithm chooses paths helps you understand the problem's complexity and the importance of ignoring negative gains.
Step 1/14
·Active fill★Answer cell
traverse
node
1
0
2
1
3
2
Result: "-inf"
traverse
1
0
node
2
1
3
2
Result: "-inf"
traverse
1
0
2
1
3
2
Result: "-inf"
traverse
1
0
2
1
3
2
Result: "-inf"
compare
1
0
node
2
1
3
2
Result: 2
move_right
1
0
node
2
1
3
2
Result: 2
traverse
1
0
2
1
node
3
2
Result: 2
traverse
1
0
2
1
3
2
Result: 2
traverse
1
0
2
1
3
2
Result: 2
compare
1
0
2
1
node
3
2
Result: 3
move_left
1
0
2
1
node
3
2
Result: 3
compare
node
1
0
2
1
3
2
Result: 6
move_left
node
1
0
2
1
3
2
Result: 6
record
1
0
2
1
3
2
Result: 6

Key Takeaways

✓ The maximum path sum can include both left and right children of a node, not just a single path downwards.

This is hard to see from code alone because the return value only represents one path, but the global max_sum tracks combined paths.

✓ Negative gains from children are ignored by taking max with 0, ensuring paths only add positive contributions.

This prevents paths with negative sums from reducing the overall maximum, a subtle but crucial insight.

✓ The recursion explores the entire tree bottom-up, computing gains from leaves up to the root, updating max_sum at each node.

Seeing the recursion order and how gains propagate clarifies the algorithm's flow better than reading code.

Practice

(1/5)
1. You are given two sorted arrays and need to find the median of their combined elements efficiently without fully merging them. Which approach guarantees the optimal time complexity for this problem?
easy
A. Merge both arrays completely and then find the median from the merged array.
B. Use binary search to partition the smaller array and find the correct partition in the other array.
C. Use a two-pointer approach to partially merge elements until the median position is reached.
D. Apply dynamic programming to store medians of subarrays and combine results.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires finding the median of two sorted arrays without fully merging them to achieve better than O(m+n) time.
  2. Step 2: Identify the optimal approach

    Binary search on the smaller array to find a partition that balances elements on both sides guarantees O(log(min(m,n))) time, which is optimal.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Binary search on partition is the known optimal solution [OK]
Hint: Optimal median uses binary search on smaller array [OK]
Common Mistakes:
  • Assuming full merge is necessary
  • Using two pointers without binary search
  • Confusing DP with median finding
2. Given the following code snippet implementing the two-pointer approach for trapping rain water, what is the value of the variable water after the first iteration of the while loop when the input is [2, 0, 2]?
easy
A. 0
B. 2
C. 1
D. 3

Solution

  1. Step 1: Initialize variables

    left=0, right=2, left_max=0, right_max=0, water=0
  2. Step 2: First iteration of while loop

    height[left]=2, height[right]=2, since height[left] is not less than height[right], else branch runs. height[right]=2 ≥ right_max=0, so right_max=2, right decrements to 1, water remains 0.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Water not added on first iteration because max updated [OK]
Hint: Water added only when current height < max height on that side [OK]
Common Mistakes:
  • Adding water before max height is updated
  • Confusing left and right pointer conditions
  • Off-by-one errors in pointer movement
3. The following code attempts to implement the optimal DP solution for the Best Time to Buy Sell IV problem. Which line contains a subtle bug that can cause incorrect results for large k?
def maxProfit(k, prices):
    n = len(prices)
    if k >= n // 2:
        profit = 0
        for i in range(1, n):
            profit += max(0, prices[i] - prices[i - 1])
        return profit
    next_dp = [[0, 0] for _ in range(k + 1)]
    curr_dp = [[0, 0] for _ in range(k + 1)]
    for i in range(n - 1, -1, -1):
        for t in range(1, k + 1):
            curr_dp[t][0] = max(-prices[i] + next_dp[t][1], next_dp[t][0])
            curr_dp[t][1] = max(prices[i] + next_dp[t - 1][0], next_dp[t][1])
        next_dp, curr_dp = curr_dp, next_dp
    return next_dp[k][0]
medium
A. Line 3: The condition should be k >= n // 2 instead of k > n // 2
B. Line 10: Using next_dp[t][1] instead of next_dp[t-1][1] in curr_dp[t][0] update
C. Line 13: Swapping next_dp and curr_dp incorrectly
D. Line 7: Summing max(0, prices[i] - prices[i - 1]) without checking if prices is empty

Solution

  1. Step 1: Analyze the unlimited transactions condition

    The code uses if k >= n // 2 to shortcut to unlimited transactions logic. This condition correctly covers the case when k equals half the number of days.
  2. Step 2: Understand impact of the bug

    Using k > n // 2 would miss the case when k == n // 2, causing inefficient DP execution or incorrect results. The corrected code uses k >= n // 2.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct condition is k >= n // 2 to handle unlimited transactions case [OK]
Hint: Check boundary conditions for unlimited transactions case [OK]
Common Mistakes:
  • Using > instead of >= in unlimited transactions check
  • Mixing holding and not holding states in DP updates
  • Incorrect dp array swapping
4. What is the time complexity of the optimal solution for Word Search II that uses backtracking with a Trie and in-place board modification, assuming the board size is NxM, the number of words is W, and the maximum length of a word is L?
medium
A. O(W * N * M * 4^L) because each word is searched independently
B. O(W * L) for building Trie plus O(N * M * 4^L) for backtracking
C. O(N * M * L * W) because Trie traversal multiplies word length and count
D. O(N * M * 4^L) due to backtracking pruning with Trie prefix checks

Solution

  1. Step 1: Identify Trie construction cost

    Building the Trie takes O(W * L) time, inserting each word character by character.
  2. Step 2: Analyze backtracking complexity

    Backtracking explores up to 4^L paths from each cell, so O(N * M * 4^L) dominates search time.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Trie build plus backtracking combined yields O(W*L + N*M*4^L) [OK]
Hint: Trie build separate from backtracking cost [OK]
Common Mistakes:
  • Confusing independent word search with Trie pruning
  • Ignoring Trie build cost
  • Multiplying all parameters incorrectly
5. Suppose the problem is modified so that the same letter cell on the board can be used multiple times within the same word search path (i.e., reuse of cells is allowed). Which modification to the optimal backtracking with Trie approach correctly handles this variant without causing infinite loops?
hard
A. Use a separate visited set to track cells per path and allow revisiting after backtracking
B. Remove the in-place marking of visited cells and rely solely on Trie pruning
C. Keep the in-place marking but reset visited cells only after exploring all neighbors
D. Modify the Trie to store counts of allowed cell reuse and decrement on each visit

Solution

  1. Step 1: Understand reuse impact on visited marking

    Allowing reuse means cells can be revisited, so marking cells as visited must be carefully managed to avoid infinite loops.
  2. Step 2: Identify correct marking strategy

    Using a separate visited set per path allows revisiting cells after backtracking, preventing infinite loops while supporting reuse.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Separate visited set per path safely handles cell reuse [OK]
Hint: Track visited cells per path to allow safe reuse [OK]
Common Mistakes:
  • Removing marking causes infinite loops
  • Using global visited set without reset
  • Modifying Trie for cell reuse incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard