KatInterview

Multi-Problem Algorithm Sprint: Trees, Grids, and Heaps

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbinary-treesbinary-search-treesgraph-traversal

Last 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