Continuous Subarray Sum

Problem

https://leetcode.com/problems/continuous-subarray-sum/arrow-up-right

Understanding of problem

The continuous subarray sum should be multiple of k , and the length of the subarray should be at least 2.

For example, if the k is 6, this is how the preSum and preSum%k looks like.

The reason for taking the modulo is beacuase we are trying to find the multiples. And the base concept is if modulo of number is zero, the number is a multiple.

As we try to find the contiguous sub-arrays, we can use the principle of prefix sum.

Store the preSum%k in HashMap with its position for easy lookup

And using the modulo congruence,

(sum2βˆ’sum1)%k=0sum2%kβˆ’sum1%k=0sum2%k=sum1%k(sum2 - sum1)\%k = 0 \\ sum2\%k - sum1\%k = 0 \\ sum2\%k = sum1\%k

This means whenever we encounter the same modulo, using the above modulo congruence relation, the subarray sum is multiple of k .

Edge case

The below case is an edge case that needs to be handled.

k = 7. We are trying to find multiples of 7

When we see the modulo as zero, even before we find a similar modulo, we need to check the length of the subarray.

In the above case, we have the subarray sum of a+b = 21. 21 is a multiple of 7. Since the problem asks to check if the length of the subarray should be at least 2, which(length) is calculated based on the values stored in the HashMap, even though it is a valid subarray, it is not counted as one and gives out false.

To handle this kind of case, we add

Putting -1 will make sure the above case is not handled correctly.

If we calculate now,

Solution

Last updated