#974

Subarray Sums Divisible by K

Medium Prefix remainders

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count the non-empty subarrays whose sum is divisible by k.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count pieces whose sum is a multiple of k.

Why this works: two prefixes with the same remainder mod k differ by a multiple of k. Count remainders as you go.

Example: [4, 5, 0, -2, -3, 1], k = 5

remainders: 4, 4, 4, 2, 4, 0 (start 0)each repeat adds the count seen so fartotal 7

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Not fixing negative remainders, so -1 and k-1 are counted as different buckets.