Subarray Sums Divisible by K (LeetCode 974): Solution and Explanation
Given an integer array nums (which may contain negatives) and an integer k, count the non-empty contiguous subarrays whose sum is a multiple of k.
Intuition
Checking every subarray means O(n²) pairs of start and end, which is too slow for 30,000 elements. The way out is the usual prefix sum trick: write prefix[p] for the sum of the first p elements, so the sum of nums[i..j] is prefix[j + 1] - prefix[i].
A difference of two numbers is divisible by k exactly when the two numbers leave the same remainder when divided by k. So a subarray works if and only if the prefix before it and the prefix at its end land in the same remainder bucket.
That turns the problem into counting pairs inside buckets. Walk the array once, keeping count[r] = how many prefixes so far have remainder r. When a new prefix lands in bucket r, it pairs with every prefix already there, so add count[r] to the answer before dropping the new prefix in.
Two details make it correct. The empty prefix (sum 0) must be in bucket 0 from the start, or subarrays that begin at index 0 are missed. And in languages where % can be negative, -2 mod 5 must become 3, not -2, or equal remainders land in different buckets.
Approach: Prefix remainders with a count array
- Create
countof size k filled with zeros and setcount[0] = 1for the empty prefix. - Set
prefix = 0andresult = 0. - For each
num, updateprefix = (prefix + num) mod k, normalised into 0..k-1. - Add
count[prefix]toresult: each earlier prefix with the same remainder closes a subarray ending here. - Increment
count[prefix]so later prefixes can pair with this one. - Return
result.
Step-by-step example
nums = [4,5,0,-2,-3,1], k = 5
- Start with bucket 0 holding the empty prefix, result = 0.
- 4: prefix mod 5 = 4. Bucket 4 is empty, result stays 0. Bucket 4 now has 1.
- 5: prefix = (4 + 5) mod 5 = 4. Bucket 4 has 1, so result = 1 (the subarray [5]). Bucket 4 now has 2.
- 0: prefix stays 4. Bucket 4 has 2, result = 3 ([5,0] and [0]). Bucket 4 now has 3.
- -2: prefix = (4 - 2) mod 5 = 2. Bucket 2 is empty, result stays 3. Bucket 2 now has 1.
- -3: prefix = (2 - 3) mod 5 = 4 after wrapping -1 up to 4. Bucket 4 has 3, result = 6 ([5,0,-2,-3], [0,-2,-3], [-2,-3]). Bucket 4 now has 4.
- 1: prefix = (4 + 1) mod 5 = 0. Bucket 0 has the empty prefix, result = 7 (the whole array). Return 7.
Code: Python, Java, C++
1class Solution:
2 def subarraysDivByK(self, nums: List[int], k: int) -> int:
3 count = [0] * k
4 count[0] = 1
5 prefix = 0
6 result = 0
7 for num in nums:
8 prefix = (prefix + num) % k
9 result += count[prefix]
10 count[prefix] += 1
11 return result1class Solution {
2 public int subarraysDivByK(int[] nums, int k) {
3 int[] count = new int[k];
4 count[0] = 1;
5 int prefix = 0, result = 0;
6 for (int num : nums) {
7 prefix = ((prefix + num) % k + k) % k;
8 result += count[prefix];
9 count[prefix]++;
10 }
11 return result;
12 }
13}1class Solution {
2public:
3 int subarraysDivByK(vector<int>& nums, int k) {
4 vector<int> count(k, 0);
5 count[0] = 1;
6 int prefix = 0, result = 0;
7 for (int num : nums) {
8 prefix = ((prefix + num) % k + k) % k;
9 result += count[prefix];
10 count[prefix]++;
11 }
12 return result;
13 }
14};Time and space complexity
O(n + k)
One pass over the array with constant work per element, plus O(k) to allocate the count array.
O(k)
The count array has one slot per possible remainder. A hash map instead uses O(min(n, k)).
Other approaches
Brute force over all subarrays (time O(n²), space O(1))
Fix each start index and extend the end while keeping a running sum, counting sums divisible by k. Simple and useful as a test oracle, but quadratic.
Count buckets, then combine (time O(n + k), space O(k))
First compute the remainder of every prefix (including the empty one) and count how many fall in each bucket. A bucket with c prefixes contributes c * (c - 1) / 2 pairs. Same idea in two passes.
Common mistakes
- Forgetting
count[0] = 1. Without the empty prefix, subarrays starting at index 0 such as the whole array in Example 1 are never counted. - Using a raw
%with negative numbers in Java, C++, C#, JavaScript or Go. -1 % 5 is -1 there, so use ((x % k) + k) % k. - Incrementing the bucket before adding it to the result, which pairs each prefix with itself and counts empty subarrays.
- Storing raw prefix sums instead of remainders. Sums can grow large, and only the remainder matters.
Frequently asked questions
Why do two prefixes with the same remainder give a valid subarray?
If prefix[j] and prefix[i] both leave remainder r, their difference leaves remainder 0, so it is a multiple of k. That difference is exactly the sum of nums[i..j-1].
How is this related to Subarray Sum Equals K?
Both count pairs of prefixes. In Subarray Sum Equals K you look up prefix - k in a hash map; here you look up the same remainder, which is why a fixed array of size k works.
How do negative numbers affect the solution?
The idea is unchanged, but the remainder must be normalised into 0..k-1. Python's % already does this; most other languages need the ((x % k) + k) % k form.
What is the time complexity of Subarray Sums Divisible by K?
O(n + k) time and O(k) space with a count array, since each element does one update and one lookup.