Count Downward Paths in a Referral Tree That Sum to a Target
Last updated: November 29, 2026
Quick Overview
Each node in a referral tree carries a reward amount, possibly negative. Count the downward paths (starting at any node, ending at any descendant or itself) whose rewards sum to a target.
Meta
November 29, 20260
0
0 solved
Each node in a referral tree carries a reward amount, possibly negative. Count the downward paths (starting at any node, ending at any descendant or itself) whose rewards sum to a target.
A Meta onsite question that combines tree DFS with the prefix sum hash map trick from arrays. The interviewer looks for the O(n) solution and for correct backtracking of the map when leaving a node.
What the Interviewer Expects
- Reduce to prefix sums along the root-to-node path
- Store counts of prefix sums in a hash map
- Seed the map with sum 0 once
- Undo the map entry when backtracking
- Explain why the O(n^2) start-at-every-node approach is slower
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
- What if paths may go up and then down through a common ancestor?
- How would you return the paths themselves?
- How does this change if all values are positive?
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 is a binary tree root (or None) and an integer target. A path goes from a node down to one of its descendants or itself along parent-child edges. Count all such paths with sum equal to `target...
High-Level Design
On the path from the root to the current node, let cur be the running sum. A downward path ending here and starting at some ancestor sums to cur - prefix where prefix is the running sum just abo...