Subarray Sum Patterns
Count subarrays with a given sum in one pass: each prefix looks up how often prefix - k occurred before.
Decision · step 2 of 10Prefix Sum and Kadane: Count subarrays summing to 7
i = 0: prefix becomes 3, so a subarray ending here sums to 7 if an earlier prefix was 3 - 7 = -4. Never seen, so none ends here. Then record prefix 3.
What you will see
Prefix sum row plus a frequency table; each step looks up prefix - k.
Cost
| Best | O(n) |
|---|---|
| Average | O(n) |
| Worst | O(n) |
| Space | O(n) |
How you work with it here
play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next.
Screen readers: Each cell is announced as index, value and state; each step's accessibility text states the decision and its effect.
Reduced motion: Swaps and shifts become value crossfades with an outline flash; pointers appear at their destination.
Before this
Related
Taught by the same lesson
Prefix Sum and Kadane covers these too, in the same run.