Count Downward Routes Whose Shipping Costs Sum to a Target
Last updated: November 29, 2026
Quick Overview
Each node of a binary routing tree holds a shipping cost, which may be negative for rebates. Count the downward paths (starting at any node and moving only to children) whose costs sum exactly to a target.
Amazon
November 29, 20260
0
0 solved
Each node of a binary routing tree holds a shipping cost, which may be negative for rebates. Count the downward paths (starting at any node and moving only to children) whose costs sum exactly to a target.
A common Amazon technical screen pattern that blends tree DFS with the prefix-sum hash map idea from arrays. The interviewer wants to see you move from the O(n^2) brute force to the O(n) prefix-sum approach and correctly undo state when backtracking.
What the Interviewer Expects
- Start with a brute force that tries every start node and explain its cost
- Recognize the prefix-sum plus hash map trick on a root-to-node path
- Seed the map with prefix 0 so paths starting at the root count
- Decrement the counter when leaving a node so sibling branches do not see stale prefixes
- Handle negative costs, which rule out sliding-window shortcuts
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
- How would you return the paths themselves instead of the count?
- What if paths could also go up through a parent and down another branch?
- How would you make this iterative for a 10^5-deep tree?
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 of a binary tree with integer values (positive, zero, or negative) and an integer target. Output: number of downward paths with sum equal to target. A path has at least one node and need n...
High-Level Design
Along the current root-to-node path, keep a running prefix sum cur and a counter of how many times each prefix sum has appeared on this path. A downward path ending at the current node sums to targe...