Practice
Solution
Step 1: Understand BST property usage
In a BST, left subtree nodes are smaller and right subtree nodes are larger than the current node. This allows pruning the search space efficiently.Step 2: Identify optimal traversal
Starting from root, if both target nodes are smaller, go left; if both are larger, go right; else current node is the split point and thus the LCA.Final Answer:
Option C -> Option CQuick Check:
Iterative BST traversal uses O(h) time and O(1) space [OK]
- Using path comparison wastes time and space
- Greedy approach ignores split point logic
- Dynamic programming is unnecessary overhead
Solution
Step 1: Check root adjustment logic
If root.val < low, root should move to root.right, not root.left, to find valid nodes.Step 2: Verify other lines
Line 5 correctly moves root to root.left if root.val > high. Lines 10 and 16 correctly adjust subtree pointers.Final Answer:
Option A -> Option AQuick Check:
Incorrect pointer move causes invalid pruning or infinite loop [OK]
- Confusing left and right subtree moves
- Incorrect pointer updates causing invalid BST
Solution
Step 1: Identify BST strict inequality
BST requires node.val to be strictly greater than previous inorder value; using < instead of <= allows duplicates.Step 2: Understand impact of bug
Using node.val < prev[0] misses the case when node.val == prev[0], incorrectly allowing duplicates and invalid BSTs.Final Answer:
Option C -> Option CQuick Check:
Strict inequality check is essential to reject duplicates [OK]
- Allowing duplicates by using < instead of <=
- Not resetting prev between calls
- Only comparing immediate children
Solution
Step 1: Understand how duplicates affect sum accumulation
Duplicates must be included in the sum for nodes with equal values to maintain correctness.Step 2: Modify accumulation logic
Accumulate sum including all nodes with values >= current node before updating node.val during reverse inorder traversal.Final Answer:
Option D -> Option DQuick Check:
Including equal values in sum ensures correct Greater Tree with duplicates [OK]
- Changing traversal order breaks sum logic
- Skipping duplicates causes incorrect sums
- Using extra data structures unnecessarily increases complexity
Solution
Step 1: Understand duplicates and two-pointer constraints
Two-pointer approach requires two distinct indices; if pointers meet, need to verify if duplicate values exist.Step 2: Modify check when left == right
Check if the value at that index occurs at least twice in the BST to allow sum with itself.Final Answer:
Option D -> Option DQuick Check:
Only During two-pointer traversal, if left == right, check if the value at that index appears at least twice in the BST. correctly handles duplicates without breaking two-pointer logic [OK]
- Allowing pointers to be equal without duplicate check
- Removing duplicates loses valid pairs
- Ignoring duplicates in hash set approach
