Multi-Problem Algorithm Sprint: Trees, Grids, and Heaps
Trees & GraphsModel answerLast updated
Implement six independent algorithm problems covering BST operations, tree traversals, optimization, and graph exploration with correctness and complexity analysis.
Implement solutions for the following six independent algorithm problems. For each, provide working code, analyze time and space complexity, and handle edge cases.
Problem 1: BST Range Sum
Given a binary search tree root and two integers low and high, compute the sum of all node values v where low <= v <= high. Leverage the BST property to prune unnecessary subtrees.
Problem 2: Lowest Common Ancestor
Given a binary tree root and two nodes p and q that exist in the tree, find their lowest common ancestor (the deepest node that has both as descendants). Implement both recursive and iterative solutions.
Problem 3: Cheapest Flight Pair
You have two lists: departures = [(date, price), ...] and returns = [(date, price), ...]. Select one departure and one return where the return date is strictly later than the departure date, minimizing total cost. If lists are pre-sorted by date, achieve O(n) time; otherwise describe an O(n log n) approach. Return the pair and total cost, or None if impossible.
Problem 4: Subtree Average Match
Count how many nodes in a binary tree have a value equal to the floor of the average of all values in their subtree (including themselves). Average is computed as floor(sum / count). Achieve O(n) time.
Problem 5: Grid Component and Boundary
Given a 2D binary grid and starting cell (r, c), return all cells that are 4-directionally connected to (r, c) with the same value. Follow-up: Also return cells adjacent to this component but with different values (the external boundary). Compare BFS and DFS approaches.
Problem 6: Max-Heap Validation
Determine if a binary tree represents a valid max-heap. This requires: (1) complete binary tree structure (all levels full except possibly the last, filled left-to-right), and (2) heap property (every node >= its children). Use a BFS approach and explain why DFS is insufficient for checking completeness.
Use this tree node definition:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Hints
Hint 1
For BST range sum, use the ordering property to skip entire subtrees that fall outside the range
Hint 2
The LCA recursive solution returns early when finding p or q, which correctly handles ancestor relationships
Hint 3
For flight optimization with sorted inputs, maintain a running minimum as you sweep through valid departures
Hint 4
Subtree average requires post-order traversal to aggregate child results before processing the parent
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
Problem 1: BST Range Sum
Strategy: Perform depth-first traversal with intelligent pruning based on BST properties.
- If
node.val < low, the entire left subtree is too small—skip it - If
node.val > high, the entire right subtree is too large—skip it - Otherwise, include the node and explore both children
Use an explicit stack to avoid recursion depth issues on skewed trees.
Complexity: O(n) worst case when the range spans the entire tree. With effective pruning, closer to O(h + k) where k is the number of in-range nodes. Space: O(h) for the stack.
def bst_range_sum(root, low, high):
if not root:
return 0
total = 0
stack = [root]
while stack:
node = stack.pop()
if not node:
continue
if low <= node.val <= high:
total += node.val
stack.append(node.left)
stack.append(node.right)
elif node.val < low:
stack.append(node.right)
else: # node.val > high
stack.append(node.left)
return total
Edge cases: Empty tree (returns 0), inverted bounds where low > high (returns 0), single-node trees.
Problem 2: Lowest Common Ancestor
Recursive approach: Each recursive call returns either p, q, their LCA, or None.
- Base case: if current node is None, p, or q, return it immediately
- Recursively search left and right subtrees
- If both sides return non-None, current node is where paths diverge (the LCA)
- Otherwise, propagate the non-None result upward
This correctly handles cases where one node is an ancestor of the other.
Complexity: O(n) time, O(h) space for recursion stack.
def find_lca_recursive(root, p, q):
if not root or root == p or root == q:
return root
left_result = find_lca_recursive(root.left, p, q)
right_result = find_lca_recursive(root.right, p, q)
if left_result and right_result:
return root
return left_result if left_result else right_result
Iterative approach: Build a parent map via BFS, then trace ancestors.
- BFS from root, recording each node's parent until both p and q are found
- Collect all ancestors of p into a set
- Walk up from q until hitting a member of p's ancestor set
Complexity: O(n) time and space.
from collections import deque
def find_lca_iterative(root, p, q):
parent_map = {root: None}
queue = deque([root])
while p not in parent_map or q not in parent_map:
node = queue.popleft()
if node.left:
parent_map[node.left] = node
queue.append(node.left)
if node.right:
parent_map[node.right] = node
queue.append(node.right)
p_ancestors = set()
current = p
while current:
p_ancestors.add(current)
current = parent_map[current]
current = q
while current not in p_ancestors:
current = parent_map[current]
return current
Problem 3: Cheapest Flight Pair
Sorted input (O(n) solution): Use two-pointer technique with a running minimum.
For each return flight, we need the cheapest departure that occurs strictly earlier. Process returns in order, maintaining the minimum-cost departure seen so far.
def cheapest_flights(departures, returns, presorted=False):
if not presorted:
departures = sorted(departures, key=lambda x: x[0])
returns = sorted(returns, key=lambda x: x[0])
dep_idx = 0
min_dep = None # (date, price)
best_solution = None # (dep, ret, total_cost)
for ret_date, ret_price in returns:
# Advance through all departures before this return
while dep_idx < len(departures) and departures[dep_idx][0] < ret_date:
dep_date, dep_price = departures[dep_idx]
if min_dep is None or dep_price < min_dep[1]:
min_dep = (dep_date, dep_price)
dep_idx += 1
# Update best if we have a valid departure
if min_dep:
total = min_dep[1] + ret_price
if best_solution is None or total < best_solution[2]:
best_solution = (min_dep, (ret_date, ret_price), total)
return best_solution
Complexity: O(n + m) when presorted, O(n log n + m log m) when sorting is needed. Space: O(1) beyond input storage.
Critical detail: Use strict inequality (<) for date comparison—same-day round trips are invalid.
Edge cases: Empty lists, no valid pairs (returns None), multiple optimal solutions (any is acceptable).
Problem 4: Subtree Average Match
Strategy: Post-order traversal where each node receives aggregated (sum, count) from its children before computing its own statistics. This avoids redundant subtree traversals.
def count_average_nodes(root):
result = 0
def postorder(node):
nonlocal result
if not node:
return 0, 0
left_sum, left_count = postorder(node.left)
right_sum, right_count = postorder(node.right)
subtree_sum = left_sum + right_sum + node.val
subtree_count = left_count + right_count + 1
if node.val == subtree_sum // subtree_count:
result += 1
return subtree_sum, subtree_count
postorder(root)
return result
Complexity: O(n) time, O(h) space for recursion. Each node is visited once, and subtree statistics are computed in constant time using child results.
Common mistake: Recomputing subtree sums from scratch at each node leads to O(n²) complexity on skewed trees.
Problem 5: Grid Component and Boundary
Flood fill: Standard BFS or DFS to explore all connected cells with matching values.
from collections import deque
def grid_component_and_border(grid, r, c):
if not grid or not grid[0]:
return set(), set()
rows, cols = len(grid), len(grid[0])
target_value = grid[r][c]
component = set()
border = set()
queue = deque([(r, c)])
component.add((r, c))
while queue:
row, col = queue.popleft()
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr, nc = row + dr, col + dc
if 0 <= nr < rows and 0 <= nc < cols:
if grid[nr][nc] == target_value:
if (nr, nc) not in component:
component.add((nr, nc))
queue.append((nr, nc))
else:
border.add((nr, nc))
return component, border
BFS vs DFS trade-offs:
- Both visit the same cells with identical asymptotic complexity
- Recursive DFS risks stack overflow on large grids (Python limit ~1000)
- BFS with a queue is stack-safe and explores in distance layers
- Iterative DFS with an explicit stack is also safe but loses layer structure
- For this problem, BFS is preferred for safety and clarity
Complexity: O(R·C) time and space worst case. More precisely O(k + b) where k is component size and b is boundary size.
Problem 6: Max-Heap Validation
Two requirements:
- Completeness: All levels filled left-to-right with no gaps
- Heap property: Every parent >= its children
Why BFS is necessary: Completeness cannot be verified with DFS because you need to detect gaps in level filling. A node at position i should have children at positions 2i+1 and 2i+2. Any gap or right child without a left child violates completeness.
from collections import deque
def is_max_heap(root):
if not root:
return True
queue = deque([(root, 0)]) # (node, index)
expected_next = 0
max_index = 0
nodes_by_index = {}
# Check completeness via indices
while queue:
node, idx = queue.popleft()
if idx != expected_next:
return False # Gap detected
nodes_by_index[idx] = node
max_index = idx
expected_next += 1
if node.left:
queue.append((node.left, 2 * idx + 1))
if node.right:
queue.append((node.right, 2 * idx + 2))
# Check heap property
for idx in range(max_index + 1):
node = nodes_by_index[idx]
left_idx, right_idx = 2 * idx + 1, 2 * idx + 2
if left_idx in nodes_by_index:
if node.val < nodes_by_index[left_idx].val:
return False
if right_idx in nodes_by_index:
if node.val < nodes_by_index[right_idx].val:
return False
return True
Complexity: O(n) time and space. Each node is visited once, and index-based validation catches structural violations efficiently.
Why DFS fails: You cannot detect a missing node in the middle of a level with DFS—you'd need global level information that DFS doesn't naturally provide.