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 numsktruekfalsekk
Example 1
Output: true
Explanation: [2, 4] adds up to 6.
Example 2
Output: true
Explanation: the whole array adds up to 42, which is 7 × 6.
Example 3
Output: false
Explanation: no subarray of two or more elements adds up to a multiple of 13.
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]k = 6
Look at the picture above. The top row is nums
The answer for this array is [2, 4][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
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
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]
If the remainder first appeared at index jij + 1ii - ji - j >= 2
A subarray that starts at index 0
Take [2, 4]k = 6
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
- First, create the map
, from each remainder to the first index where the running total left it, and put in the empty start: remainder 0 at index -1.firstIndex - Walk through the array with a loop over
. At each element, add it to the running total and keep only the remainder after dividing byi , ink .remainder is Java's remainder operator.% - Look the remainder up and store it in one call,
. It stores the index only if the remainder is new, and returns the earlier index if there is one. That earlier index goes intoputIfAbsent , which isj if the remainder is new.null - If there is an earlier index and
, the elements between the two indexes form a subarray of at least two elements whose sum is a multiple ofi - j >= 2 , so return true.k - If the loop ends without that, return false.
The main
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:
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]false
Look at the fourth line. [6]k = 6false[2, 4]
The last line, [5, 0, 0, 0]k = 3putIfAbsentputfalse[0, 0]
The original implementation,
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
. Each element costs one addition, one remainder and onenums , which takes constant time on average in aputIfAbsent .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