Problem
FAANG · LeetCode #974

Subarray Sums Divisible by K — three-stage drill

1The ProblemMedium

Subarray Sums Divisible by K

Count contiguous subarrays whose sum is divisible by k.

count subarrays with sum divisible by5405102-23-34155 + 0 = 55 + 0 − 2 − 3 = 0… 7 in totalreturn7
Examples
[4,5,0,-2,-3,1], k=5→ 7[1,2,3], k=7→ 0

constraintValues may be negative (use ((p % k) + k) % k).

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 → 7

Step through it

k = 5nums450-2-31prefix012345↩ ANSWERcount =0remainder → times seenseen = {0: 1}
start: seen = {0: 1}, count = 0
Step 1 / 8
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent