Count Downward Call Chains Whose Costs Sum to a Target
Last updated: November 29, 2026
Quick Overview
In a binary tree of RPC calls, each node holds the cost of one call. Count the downward paths (starting at any node and ending at any descendant or itself) whose costs sum exactly to a target.
0
0
0 solved
In a binary tree of RPC calls, each node holds the cost of one call. Count the downward paths (starting at any node and ending at any descendant or itself) whose costs sum exactly to a target.
A Google onsite question that moves the prefix-sum trick from arrays onto trees. The interviewer first accepts the O(n^2) double recursion, then pushes for O(n) with a running prefix-sum counter that is undone on backtrack.
What the Interviewer Expects
- Start with the O(n^2) brute force and its cost
- Map the array prefix-sum idea onto root-to-node paths
- Seed the counter with prefix 0 so paths starting at the root count
- Undo the counter on backtrack so sibling subtrees do not see each other
- Handle negative costs correctly
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the actual paths, not just the count.
- What if paths may go up and then down through a turning node?
- Make it iterative for very deep trees.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: root and integer target. Output: number of downward paths with sum equal to target. Paths have at least one node, must go parent to child, and costs may be negative (refunds), so pruning on s...
High-Level Design
Let P(x) be the sum from the root to node x. A downward path from u (exclusive ancestor) to x sums to P(x) - P(u). So at each node, the number of valid paths ending here equals the number of ances...