Continuous Subarray Sum

Find a run of neighbouring numbers whose sum divides evenly by k, by watching the remainders of a running total.

You are given an array nums of non-negative integers and a positive integer k. Return true if some run of at least two neighbouring elements adds up to a multiple of k, and false otherwise. Such a run of neighbouring elements is called a subarray. A multiple of k is k times a whole number, so 0 counts too.

Example 1
Input: nums = [23, 2, 4, 6, 7], k = 6
Output: true
Explanation: [2, 4] adds up to 6.
Example 2
Input: nums = [23, 2, 6, 4, 7], k = 6
Output: true
Explanation: the whole array adds up to 42, which is 7 × 6.
Example 3
Input: nums = [23, 2, 6, 4, 7], k = 13
Output: false
Explanation: no subarray of two or more elements adds up to a multiple of 13.
Solution

The Idea

Think of packing eggs into boxes of 6. With 23 eggs you fill 3 boxes and have 5 loose eggs left over. That left-over count is the remainder after dividing by 6. A number is a multiple of 6 exactly when it fills whole boxes, with a remainder of 0.

Now take Example 1, [23, 2, 4, 6, 7] with k = 6, and add the numbers from left to right. After each step, write down the total so far, called the running total, and its remainder after dividing by 6.

The array 23, 2, 4, 6, 7 with its running totals 23, 25, 29, 35, 42 and their remainders after dividing by 6: 5, 1, 5, 5, 0. The running totals 23 and 29 leave the same remainder, 5, and the numbers between them, 2 and 4, add up to 6.

Look at the picture above. The top row is nums, with its index under each element. The middle row holds the running totals: 23, then 23 + 2 = 25, then 29, 35 and 42. The bottom row holds their remainders after dividing by 6: 5, 1, 5, 5 and 0.

The answer for this array is [2, 4], marked in orange. But an array can have many subarrays, and adding up each one separately takes a long time. Is there a sign in the bottom row that points at [2, 4]?

There is. The running total at index 0 is 23 and leaves 5 loose eggs. At index 2 it is 29 and again leaves 5. Going from 23 to 29 we added 2 and 4, and the loose count came back to where it was. So those 6 eggs filled whole boxes, with nothing left over: 29 - 23 = 6 is a multiple of 6.

This works for any two places in the row. When the remainder repeats, the elements added in between sum to a multiple of k. So instead of adding up subarrays, we only need to spot a remainder we have seen before.

Solution Approach

Turning that idea into code means settling three things: how to spot a repeated remainder, which index to remember for each remainder, and how to catch a subarray that starts at index 0.

Spotting a repeated remainder

How do we know whether a remainder appeared before? The simple way is to compare every pair of positions, which means trying every subarray. For an array of n elements that is about n × n / 2 pairs, which gets slow quickly.

Instead, walk through the array once and keep a HashMap from each remainder to the index where it appeared. At each step, one lookup tells us whether the current remainder is already in the map.

Which index to remember

The bottom row in the picture shows 5 three times, at indexes 0, 2 and 3. Which of them should the map keep? Indexes 2 and 3 are only one step apart: 35 - 29 = 6 is the single element [6], and a subarray must have at least two elements.

If the remainder first appeared at index j and appears again at index i, the subarray runs from j + 1 to i and has i - j elements. Keeping the first index for each remainder makes that length as large as possible, so the check i - j >= 2 has the best chance to pass. A later repeat never replaces it.

A subarray that starts at index 0

Take [2, 4] with k = 6. The running totals are 2 and 6, with remainders 2 and 0. Nothing repeats, yet the whole array adds up to 6. What is missing?

The running total before the first element, which is 0. We call it the empty start: its remainder is 0, and it sits just before index 0, at index -1. Putting remainder 0 at index -1 into the map before the loop starts makes the 0 at index 1 a repeat, with length 1 - (-1) = 2.

Java Solution

The method checkSubarraySum works in these steps:

  1. First, create the map firstIndex, from each remainder to the first index where the running total left it, and put in the empty start: remainder 0 at index -1.
  2. Walk through the array with a loop over i. At each element, add it to the running total and keep only the remainder after dividing by k, in remainder. % is Java's remainder operator.
  3. Look the remainder up and store it in one call, putIfAbsent. It stores the index only if the remainder is new, and returns the earlier index if there is one. That earlier index goes into j, which is null if the remainder is new.
  4. If there is an earlier index and i - j >= 2, the elements between the two indexes form a subarray of at least two elements whose sum is a multiple of k, so return true.
  5. If the loop ends without that, return false.

The main method runs the three examples, then four small arrays: one element alone, a subarray starting at index 0, a sum of 0, and one remainder repeated four times.

Java
import java.util.HashMap;
import java.util.Map;

public class ContinuousSubarraySum {

    public static boolean checkSubarraySum(int[] nums, int k) {
        Map<Integer, Integer> firstIndex = new HashMap<>();   // remainder -> first index
        firstIndex.put(0, -1);                                // the empty start, before index 0
        int remainder = 0;
        for (int i = 0; i < nums.length; i++) {
            remainder = (remainder + nums[i]) % k;            // remainder of the running total
            Integer j = firstIndex.putIfAbsent(remainder, i); // earlier index, or null if new
            if (j != null && i - j >= 2) {
                return true;                                  // nums[j+1..i] is a multiple of k
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(checkSubarraySum(new int[] {23, 2, 4, 6, 7}, 6));
        System.out.println(checkSubarraySum(new int[] {23, 2, 6, 4, 7}, 6));
        System.out.println(checkSubarraySum(new int[] {23, 2, 6, 4, 7}, 13));
        System.out.println(checkSubarraySum(new int[] {6}, 6));          // one element only
        System.out.println(checkSubarraySum(new int[] {2, 4}, 6));       // starts at index 0
        System.out.println(checkSubarraySum(new int[] {0, 0}, 1));       // a sum of 0
        System.out.println(checkSubarraySum(new int[] {5, 0, 0, 0}, 3)); // one remainder 4 times
    }
}

Running it prints:

Output
true
true
false
false
true
true
true

The first three lines match the examples. In Example 2, the remainders after dividing by 6 are 5, 1, 1, 5 and 0. The 1 at index 2 comes only one step after the 1 at index 1, so the loop goes on. The 5 at index 3 matches the 5 at index 0, so [2, 6, 4] adds up to 12, a multiple of 6. The method stops there, before it reaches the whole array from the example. In Example 3, the remainders after dividing by 13 are 10, 12, 5, 9 and 3. None repeats and none is 0, so the answer is false.

Look at the fourth line. [6] with k = 6 reaches remainder 0 at index 0, which matches the empty start, but that subarray has one element, so the answer is false. The fifth line is [2, 4], found only because of the empty start. The sixth line shows that a sum of 0 counts: 0 + 0 is a multiple of 1.

The last line, [5, 0, 0, 0] with k = 3, is where the first index matters. The remainder is 2 at every index. With putIfAbsent, index 0 stays in the map, and index 2 is two steps after it. With plain put, each repeat would replace the stored index with the one just before it. Every gap would then be 1, and the method would return false, although [0, 0] adds up to 0.

The original implementation, ContiguousSubArraySum.java, is on GitHub.

Complexity

The method walks through the array once and does a fixed amount of work for each element.

  • Time: O(n), where n is the length of nums. Each element costs one addition, one remainder and one putIfAbsent, which takes constant time on average in a HashMap.
  • Space: O(min(n, k)). The map holds one entry per distinct remainder. There are only k possible remainders, 0 to k - 1, and at most n + 1 running totals, counting the empty start.

For a related problem that looks for subarrays adding up to exactly k, using running totals in the same way, see Subarray Sum Equals K.