Solve binary tree, grid, and heap tasks
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: Solve binary tree, grid, and heap tasks evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Range Sum of a BST (DFS with pruning)
Constraints
- 0 <= number of nodes <= 10^4
- Node values and low, high fit in a 32-bit integer
- The tree satisfies the BST property
- low <= high
Examples
Input: ([10, 5, 15, 3, 7, None, 18], 7, 15)
Expected Output: 32
Explanation: In-range values are 10, 7, and 15 -> 32. Node 18 and 3 are excluded.
Input: ([10, 5, 15, 3, 7, 13, 18, 1, None, 6], 6, 10)
Expected Output: 23
Explanation: In-range values: 10, 7, 6 -> 23.
Input: ([], 1, 10)
Expected Output: 0
Explanation: Empty tree sums to 0.
Input: ([5], 5, 5)
Expected Output: 5
Explanation: Single node inside the inclusive bound.
Input: ([5], 6, 10)
Expected Output: 0
Explanation: Single node outside the range.
Hints
- DFS (stack or recursion) is the natural fit for subtree aggregation.
- Prune: only recurse left when node.val > low; only recurse right when node.val < high.
- Add node.val to the running sum exactly when low <= node.val <= high.
Lowest Common Ancestor in a Binary Tree
Constraints
- 2 <= number of nodes <= 10^4
- Node values are unique
- p and q are distinct values that both exist in the tree
- The tree may be arbitrary (not a BST)
Examples
Input: ([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 1)
Expected Output: 3
Explanation: 5 is in the left subtree, 1 in the right; their LCA is the root 3.
Input: ([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 4)
Expected Output: 5
Explanation: 4 is a descendant of 5, so 5 is its own ancestor and the LCA.
Input: ([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 7, 4)
Expected Output: 2
Explanation: Both 7 and 4 are children of node 2.
Input: ([1, 2], 1, 2)
Expected Output: 1
Explanation: 2 is a child of the root 1.
Input: ([1], 1, 1)
Expected Output: 1
Explanation: Degenerate p == q on the only node.
Hints
- Recurse: if a node equals p or q, return it upward.
- If both the left and right recursive calls return non-null, the current node is the LCA.
- Otherwise propagate up whichever side found a target.
- Alternative: BFS to build a child->parent map, walk p's ancestors into a set, then walk q's ancestors until one is in the set.
Minimum Round-Trip Flight Cost
Constraints
- 0 <= len(departures), len(returns) <= 10^5
- dates and prices are non-negative integers
- A valid pair requires return_date strictly greater than depart_date
- Return None/null when no return date is later than any departure date
Examples
Input: ([[1, 100], [3, 50], [5, 200]], [[2, 80], [4, 40], [6, 300]])
Expected Output: [3, 4, 90]
Explanation: Depart day 3 ($50) + return day 4 ($40) = $90, the cheapest feasible combination.
Input: ([[1, 100]], [[2, 200]])
Expected Output: [1, 2, 300]
Explanation: Only one feasible pair.
Input: ([[5, 10]], [[1, 10]])
Expected Output: null
Explanation: The only return date (1) precedes the only departure date (5): infeasible.
Input: ([], [[1, 10]])
Expected Output: null
Explanation: No departures.
Input: ([[1, 100], [2, 90], [3, 80]], [[1, 50]])
Expected Output: null
Explanation: The lone return date 1 is not strictly after any departure date.
Input: ([[10, 5], [2, 100]], [[3, 1], [11, 1]])
Expected Output: [10, 11, 6]
Explanation: For return day 11 the cheapest earlier departure is day 10 ($5): total $6, beating return day 3 (forced to depart day 2 at $100).
Hints
- Sort departures and returns by date.
- Sweep returns in increasing date order; before pricing a return, fold in every departure with an earlier date and track the minimum departure price so far.
- The minimum departure price is monotonic as the return date grows, giving an O(n) sweep after sorting.
- Guard the infeasible case: if no departure precedes any return, answer is None.
Count Nodes Equal to Subtree Average
Constraints
- 0 <= number of nodes <= 10^4
- Node values fit in a 32-bit integer (use 64-bit accumulators for subtree sums)
- Average is floor(sum / size)
- Leaf nodes always satisfy the condition (avg of one value is the value)
Examples
Input: ([4, 8, 5, 0, 1, None, 6],)
Expected Output: 5
Explanation: Leaves 0, 1, 6 qualify; node 5's subtree {5,6} avg 5; root's subtree sum 24/6 = 4. Node 8's subtree {8,0,1} avg 3 != 8. Total 5.
Input: ([1],)
Expected Output: 1
Explanation: Single leaf: average equals its own value.
Input: ([],)
Expected Output: 0
Explanation: Empty tree.
Input: ([5, 3, 7],)
Expected Output: 3
Explanation: Leaves 3 and 7 qualify; root subtree sum 15/3 = 5 == 5.
Input: ([10, 2, 2],)
Expected Output: 2
Explanation: Both leaf 2s qualify; root 14/3 = 4 != 10.
Input: ([2, 1, 4],)
Expected Output: 3
Explanation: Leaves 1 and 4 qualify; root 7/3 floor = 2 == 2.
Hints
- Post-order DFS: return (sum, size) for each subtree.
- At each node, sum = left_sum + right_sum + val and size = left_size + right_size + 1.
- Increment the counter when sum // size == node.val (floor division).
- Use 64-bit accumulators to avoid overflow on large subtrees in typed languages.
0/1 Image Cluster and Border Neighbors
Constraints
- 1 <= R, C <= 1000
- Each grid cell is 0 or 1
- 0 <= r < R and 0 <= c < C for a valid start
- Connectivity is 4-directional (up/down/left/right)
Examples
Input: ([[1, 1, 0], [1, 0, 0], [0, 0, 1]], 0, 0)
Expected Output: [[[0, 0], [0, 1], [1, 0]], [[0, 2], [1, 1], [2, 0]]]
Explanation: The 1-component is the L-shape at (0,0),(0,1),(1,0); its in-bounds non-component neighbors are (0,2),(1,1),(2,0).
Input: ([[1]], 0, 0)
Expected Output: [[[0, 0]], []]
Explanation: Single cell, no neighbors, empty border.
Input: ([[0, 0], [0, 0]], 1, 1)
Expected Output: [[[0, 0], [0, 1], [1, 0], [1, 1]], []]
Explanation: All zeros are one component covering the whole grid; no border cells exist.
Input: ([[1, 0, 1], [0, 1, 0], [1, 0, 1]], 1, 1)
Expected Output: [[[1, 1]], [[0, 1], [1, 0], [1, 2], [2, 1]]]
Explanation: The center 1 is isolated; its four orthogonal neighbors are all border cells.
Input: ([[1, 1, 1]], 0, 1)
Expected Output: [[[0, 0], [0, 1], [0, 2]], []]
Explanation: The whole single row is one component; no in-bounds non-component neighbors.
Hints
- Flood-fill from (r, c), expanding only into neighbors with the same value.
- Track component membership in a visited set so border detection can test 'not in component'.
- For the border, scan each component cell's 4 in-bounds neighbors and collect those outside the component (dedup with a set).
- BFS uses a queue (bounded by frontier width); DFS uses the call stack (risk of overflow on huge components) - both are O(R*C).
Validate a Max-Heap Binary Tree (BFS)
Constraints
- 0 <= number of nodes <= 10^4
- An empty tree is treated as a valid (vacuous) max-heap
- Completeness means no real node appears after a missing slot in BFS order
- Heap order compares each node against its present children only
Examples
Input: ([9, 7, 8, 3, 6, 2, 1],)
Expected Output: true
Explanation: Complete tree and every parent >= its children.
Input: ([9, 7, 8, 3, 6],)
Expected Output: true
Explanation: Last level filled left-to-right with no gaps; heap order holds.
Input: ([9, 10, 8],)
Expected Output: false
Explanation: Child 10 exceeds parent 9, breaking heap order.
Input: ([9, 7, 8, None, 6],)
Expected Output: false
Explanation: A real node (6) follows a missing slot in level order, breaking completeness.
Input: ([5],)
Expected Output: true
Explanation: Single node is trivially a valid max-heap.
Input: ([],)
Expected Output: true
Explanation: Empty tree is vacuously valid.
Input: ([9, 7, 8, 3, 3, 8, 8],)
Expected Output: true
Explanation: Ties allowed: parent >= child includes equality.
Hints
- Use BFS and enqueue both children (even null ones) so gaps surface in order.
- Maintain a 'seen a gap' flag; if you later dequeue a real node after a gap, completeness is violated.
- For heap order, fail fast if any child's value exceeds its parent's value.
- An empty tree and a single node are both valid max-heaps.