Problem Statement
Pattern: Pattern Prefix Array
Solution
public static boolean checkSubArraySum(int[] nums, int k) {
if (k == 0) return true;
Map<Integer, Integer> map = new HashMap<>();
int currSumMod = 0, index = -1;
map.put(currSumMod,index++);
for (; index < nums.length; index++) {
// currSumMod is mod of sum so far
currSumMod = (currSumMod + nums [index]) % k;
// get prevIndex of currSumMod
Integer prevIndex = map.get(currSumMod);
// if prevIndex exists
if (prevIndex != null) {
// and index - prevIndex > 1
if (index - prevIndex > 1) return true;
}
// else insert index for currSumMod
else map.put(currSumMod, index);
}
return false;
}Notes
- We simply store the
Mod kof the current sum, in currSumMod - If currSumMod gets repeated, then we know that the numbers in between the
prevIndexand currentindexmust add upto some multiple ofk- For e.g. in case of the array
[23,2,6,4,7]andk=6the running sum is[23,25,31,35,42]and the remainders are[5,1,1,5,0]. We got remainder 5 at index 0 and at index 3. That means, in between these two indexes we must have added a number which is multiple of the k.
- For e.g. in case of the array
- Edge case: we initialise map with
currSumMod = 0andindex = -1since sum starts with 0, and we store it before the start of the array soindex-prevIndex > 1works- say at
index = 1currSumMod is 0.nums[0] + nums[1] == n . k(some multimple of k). - in that case it will look for
0in the map, andif (index - prevIndex > 1)willreturn truelike it should!
- say at