Subarrays with Sum Divisible by k

hard Arrays

Problem

Count the non-empty continuous parts (subarrays) of the array whose sum is divisible by k (k >= 1). Numbers can be negative. Use prefix sums and a count of remainders: O(n).

Constraints

  • 1 <= n <= 10^5
  • 1 <= k <= 10^4
  • |value| <= 10^4

Examples

Input

6
4 5 0 -2 -3 1
5

Output

7

Solutions

Best approachTime O(n + k)Space O(k)

If two prefix sums leave the same remainder when divided by k, the part between them has a sum that is a multiple of k. So we only count pairs of equal remainders. The same trick works for 'sum equals k' with a hash map.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count subarrays.
 * Input   : n, array, k.
 * Output  : The count.
 * Approach: Prefix remainders.
 * Time    : O(n + k)
 * Space   : O(k)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a, int k) {
        // Step 1: seen[r] counts how many prefix sums so far had the remainder r. The empty prefix has remainder 0.
        long[] seen = new long[k];
        seen[0] = 1;
        long prefix = 0;
        long pairs = 0;
        for (int value : a) {
            // Step 2: Keep the remainder between 0 and k - 1. In Java % can be negative, so we fix it.
            prefix = ((prefix + value) % k + k) % k;
            // Step 3: Two prefix sums with the same remainder have a sum divisible by k between them.
            pairs += seen[(int) prefix];
            seen[(int) prefix]++;
        }
        return pairs;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        int k = scanner.nextInt();
        System.out.println(solve(a, k));
    }
}
Hints (1)
  1. Why must the empty prefix count as remainder 0?