Product of array except self
- CH3 suffix
Running products from each end: everything left of i, times everything right of it.
Step through it →A prefix sum is the running total up to each point, so any stretch's sum is one subtraction: the total at its end minus the total before its start.
The map starts as {0: 1}, and each total is recorded right after its lookup. So a lookup at i sees every earlier boundary, the start of the array included, and never i itself.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
Without the {0: 1} seed, [3, 4] has no earlier total to match, and the count comes out 1, not 2.
Running products from each end: everything left of i, times everything right of it.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def subarray_sum(nums, k): frequency = {0: 1} current = answer = 0 for x in nums: current += x answer += frequency.get(current - k, 0) frequency[current] = frequency.get(current, 0) + 1 return answer