Problem
FAANG · LeetCode #560

Subarray Sum Equals K — three-stage drill

1The ProblemMedium

Subarray Sum Equals K

Count contiguous subarrays whose sum equals k (values may be negative).

count subarrays with sum =44021-2243244 = 44 + 2 − 2 = 42 − 2 + 4 = 4−2 + 4 + 2 = 44 = 4return5
Examples
[4,2,-2,4,2], k=4→ 5[1,2,3], k=10→ 0

constraintValues may be negative.

2The PatternTIME O(n) · SPACE O(n)

Prefix Sum

Running cumulative totals turn range-sum questions into O(1) lookups.

numsprefix2132420316283124sweep›prefix[i] = nums[0] + … + nums[i] → any range sum in O(1)
Problems using this pattern
3The SolutionRESULT → 5

Step through it

k = 4nums42-242prefix01234↩ ANSWERcount =0prefix sum → times seenseen = {0: 1}
start: seen = {0: 1}, count = 0
Step 1 / 7
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent