Path Sum III

MediumTreesprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree and an integer targetSum, count the paths whose node values add up to exactly targetSum. A path here does **not** need to start at the root or end at a leaf, but it must go **downward**: it is a sequence of one or more nodes where each node is the child of the previous one. Two paths are different if they use different sets of nodes. Return the count. A brute-force check of every start node is O(n^2) on skewed trees; a running prefix-sum map along the current root-to-node path brings it to O(n).

Examples

Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
The paths are 5 -> 3, 5 -> 2 -> 1, and -3 -> 11.
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3
The paths are 5 -> 4 -> 11 -> 2, 5 -> 8 -> 4 -> 5, and 4 -> 11 -> 7.

Constraints

  • 0 <= number of nodes <= 1000
  • -1000 <= Node.val <= 1000
  • -10^6 <= targetSum <= 10^6

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems