Subarray Sums Divisible by K

Medium Arrays & Hashing Prefix Sum Strategy

Subarray Sums Divisible by K is a medium arrays & hashing problem solved with the prefix sum strategy pattern. The best approach, optimal (prefix remainders + counting), runs in O(n + k) time and O(k) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (every start, running sum) up.

Problem

Given an integer array nums (values may be negative) and an integer k, return the number of non-empty contiguous subarrays whose sum is divisible by k.

A sum s is divisible by k when s is a multiple of k; zero counts, since 0 = 0 · k.

Examples

Example 1

Input
nums = [3, 1, 2, 5, -4], k = 3
Output
4
Why
The subarrays [3] (sum 3), [3, 1, 2] (sum 6), [1, 2] (sum 3) and [2, 5, -4] (sum 3) are all divisible by 3. No other subarray is.

Example 2

Input
nums = [-1, 5, -3], k = 4
Output
1
Why
Only [-1, 5] works: its sum is 4. The other sums are -1, 5, -3, 2 and 1, and none of them is a multiple of 4.

Example 3

Input
nums = [5], k = 9
Output
0
Why
The only subarray is [5], and 5 is not a multiple of 9.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • 2 <= k <= 10^4

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 57 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (every start, running sum)O(n²)O(1)
Optimal (prefix remainders + counting)O(n + k)O(k)

1Brute force (every start, running sum)

TimeO(n²)There are n(n + 1)/2 pairs (start, end), each handled in constant time.
SpaceO(1)Only the running sum and the count.

Fix the start of the subarray, then extend the end one element at a time while keeping a running sum. Every time the running sum is a multiple of k, one more subarray is found.

  1. For each start i, set sum = 0.
  2. For each end j from i to n - 1, add nums[j] to sum.
  3. If sum % k == 0, increase the count.
  4. Return the count.
class Solution {
    public int subarraysDivByK(int[] nums, int k) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                if (sum % k == 0) count++;
            }
        }
        return count;
    }
}

2Optimal (prefix remainders + counting)

TimeO(n + k)One pass over the array with constant work per element, plus allocating the k counters.
SpaceO(k)One counter per possible remainder.

A subarray's sum is the difference of two prefix sums, and a difference is divisible by k exactly when the two prefix sums have the same remainder modulo k. Walk the array keeping the running prefix sum's remainder (shifted into 0..k-1 when it is negative). Each earlier prefix with the same remainder is the start of one valid subarray ending here, so add how many there were, then record the current remainder.

  1. Make an array seen of size k, with seen[0] = 1 for the empty prefix.
  2. Keep prefix = 0 and count = 0.
  3. For each x: prefix = ((prefix + x) % k + k) % k.
  4. Add seen[prefix] to count, then increase seen[prefix].
  5. Return count.
class Solution {
    public int subarraysDivByK(int[] nums, int k) {
        int[] seen = new int[k];
        seen[0] = 1;
        int prefix = 0, count = 0;
        for (int x : nums) {
            prefix = ((prefix + x) % k + k) % k;
            count += seen[prefix];
            seen[prefix]++;
        }
        return count;
    }
}

Edge cases to test

  • A single element (answer 0 or 1)
  • Negative values (the remainder of a negative prefix sum must be shifted into 0..k-1)
  • Zeros (every zero on its own is divisible by k)
  • Every element a multiple of k (all n(n+1)/2 subarrays count)
  • Nothing divisible at all (answer 0)

Hints

Hint 1

The sum of nums[i..j] is prefix[j + 1] - prefix[i], where prefix[t] is the sum of the first t elements.

Hint 2

A difference is divisible by k exactly when both numbers leave the same remainder when divided by k.

Hint 3

Count how many earlier prefixes have each remainder. Remember the empty prefix (remainder 0), and turn negative remainders into positive ones by adding k.

FAQ

What is the best time complexity for Subarray Sums Divisible by K?

Optimal (prefix remainders + counting) runs in O(n + k) time and O(k) extra space. One pass over the array with constant work per element, plus allocating the k counters.

Which pattern does Subarray Sums Divisible by K use?

It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.

Is there a brute force solution for Subarray Sums Divisible by K?

Yes. Brute force (every start, running sum) takes O(n²) time and O(1) space. Fix the start of the subarray, then extend the end one element at a time while keeping a running sum.

Which edge cases should I test for Subarray Sums Divisible by K?

A single element (answer 0 or 1); Negative values (the remainder of a negative prefix sum must be shifted into 0..k-1); Zeros (every zero on its own is divisible by k); Every element a multiple of k (all n(n+1)/2 subarrays count); Nothing divisible at all (answer 0).