@@ -33,7 +33,8 @@ We can use prefix sums. Say P[i+1] = A[0] + A[1] + ... + A[i], where A[i] = 1 if
3333 - LC 325
3434 - Count Number of Nice Subarrays
3535 - LC 1248
36- - Continuous Subarray Sum
36+ - Continuous Subarray Sum (preSum with mod)
37+ - https://github.com/yennanliu/CS_basics/blob/master/doc/pic/presum_mod.png
3738 - LC 523
3839 - Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
3940 - LC 1343
@@ -222,4 +223,39 @@ class Solution(object):
222223 if acc - k in dic:
223224 result = max (result, i - dic[acc- k])
224225 return result
226+ ```
227+
228+ ### 2-5) Continuous Subarray Sum
229+
230+ ``` java
231+ // java
232+ // LC 523
233+ // V1
234+ // IDEA : HASHMAP
235+ // https://leetcode.com/problems/continuous-subarray-sum/editorial/
236+ // https://github.com/yennanliu/CS_basics/blob/master/doc/pic/presum_mod.png
237+ public boolean checkSubarraySum_1(int [] nums, int k) {
238+ int prefixMod = 0 ;
239+ HashMap<Integer , Integer > modSeen = new HashMap<> ();
240+ modSeen. put(0 , - 1 );
241+
242+ for (int i = 0 ; i < nums. length; i++ ) {
243+ /**
244+ * NOTE !!! we get `mod of prefixSum`, instead of get prefixSum
245+ */
246+ prefixMod = (prefixMod + nums[i]) % k;
247+
248+ if (modSeen. containsKey(prefixMod)) {
249+ // ensures that the size of subarray is at least 2
250+ if (i - modSeen. get(prefixMod) > 1 ) {
251+ return true ;
252+ }
253+ } else {
254+ // mark the value of prefixMod with the current index.
255+ modSeen. put(prefixMod, i);
256+ }
257+ }
258+
259+ return false ;
260+ }
225261```
0 commit comments