MrainW's Home

All things come to those who wait!

0%

LeetCode 523. Continuous Subarray Sum

Question

Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise.

An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.

https://leetcode.com/problems/continuous-subarray-sum/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
int sum = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
for (int i = 0; i < nums.length; i++){
sum += nums[i];
if (k != 0) sum %= k;
if (map.containsKey(sum)){
if (i - map.get(sum) > 1) return true;
} else map.put(sum, i);
}
return false;
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(n)

Welcome to my other publishing channels