15. Path Sum
easyAsked at SpotifyDetermine if the tree has a root-to-leaf path that sums to a target.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path where the sum of values along the path equals targetSum.
Constraints
0 <= nodes <= 5000-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Examples
Example 1
root=[5,4,8,11,null,13,4,7,2,null,null,null,1], target=22trueExample 2
root=[1,2,3], target=5falseApproaches
1. Enumerate all paths
Generate every root-to-leaf list of values, then check sums
- Time
- O(n^2)
- Space
- O(n^2)
// build all path arrays, sum each, compare to target — wastes both time and memoryTradeoff:
2. DFS with remaining sum
Subtract node value from the remaining target. Leaf hits when remaining equals leaf's value.
- Time
- O(n)
- Space
- O(h)
function hasPathSum(root, target) {
if (!root) return false;
if (!root.left && !root.right) return target === root.val;
return hasPathSum(root.left, target - root.val)
|| hasPathSum(root.right, target - root.val);
}Tradeoff:
Spotify-specific tips
Spotify uses sum-along-path patterns when computing aggregated listen-counts up a genre tree, so naming the recurrence in plain English earns bonus signal.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Path Sum and other Spotify interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →