Python coding

Count runs with a sum divisible by k

Given a list of integers nums (it may be empty and may hold negatives and zeros) and a positive integer k, return how many non-empty contiguous subarrays have a sum that is a multiple of k. A sum of 0 counts. Subarrays at different positions count separately, even when they hold the same values.

Aim for one pass over nums.

Besides the tests, one large input (4,000 numbers) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • count_divisible([2,-6,3,1,4,-5], 4) → 7
  • count_divisible([3,1,2], 3) → 3
  • count_divisible([7], 7) → 1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Let P[j] be the sum of the first j numbers. The sum of nums[i:j] is P[j] - P[i], a multiple of k exactly when P[i] and P[j] leave the same remainder mod k.

Hint 2

Count how many prefixes left each remainder, starting from {0: 1} for the empty prefix. Each new prefix adds the count of its remainder, then joins it.

Hint 3

Python's % returns 0 to k − 1 for a positive k, even for negatives. In Java or C++ -1 % 5 is -1: add k before comparing.

Solution and why it works
pythonO(n) · O(min(n, k))
def count_divisible(nums: list[int], k: int) -> int:
    seen = {0: 1}                        # the empty prefix has remainder 0
    rem = count = 0
    for x in nums:
        rem = (rem + x) % k              # Python's % is never negative for k > 0
        count += seen.get(rem, 0)        # each earlier equal remainder closes a run
        seen[rem] = seen.get(rem, 0) + 1
    return count

P[j] - P[i] is divisible by k exactly when both prefixes leave the same remainder, so the answer is the number of pairs of prefixes with equal remainders. A map from remainder to count adds all those pairs in one O(n) pass. Seed it with {0: 1}, or runs that start at index 0 are missed. Negatives are the trap outside Python: in Java or C++ -1 % 5 is -1, so -1 and 4 would count as different remainders unless you add k.