Skip to content
BytePatterns

Subarray Sums Divisible by K

MediumArrays#prefix-sums#hash-map#modular-arithmetic~25m

Problem

A ledger holds daily balance changes, some of them negative. Given the list nums and a positive whole number k, count the contiguous, non-empty stretches of days whose total change is a multiple of k. A total of 0 counts, since 0 is a multiple of every k.

Examples

Input:  nums = [2, -2, 3, 1, 5], k = 3
Output: 6
Why:    [2, -2], [3], [2, -2, 3], [1, 5], [3, 1, 5] and the whole list
Input:  nums = [1, 1], k = 5
Output: 0
Why:    the possible totals are 1, 1 and 2
Input:  nums = [7], k = 7
Output: 1
Why:    edge case, a single day whose change is exactly k

Hints

0 / 3

Stuck on the idea rather than the code? Prefix Sums covers it.