Last updated on October 5th, 2024 at 04:51 pm
Here, We see Continuous Subarray Sum LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Dynamic Programming, Math
Companies
Level of Question
Medium
Continuous Subarray Sum LeetCode Solution
Table of Contents
Problem Statement
Given an integer array nums and an integer k, return true
if nums
has a good subarray or false
otherwise.
A good subarray is a subarray where:
- its length is at least two, and
- the sum of the elements of the subarray is a multiple of
k
.
Note that:
- A subarray is a contiguous part of the array.
- An integer
x
is a multiple ofk
if there exists an integern
such thatx = n * k
.0
is always a multiple ofk
.
Example 1:
Input: nums = [23,2,4,6,7], k = 6
Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
Example 2:
Input: nums = [23,2,6,4,7], k = 6
Output: true
Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.
Example 3:
Input: nums = [23,2,6,4,7], k = 13
Output: false
1. Continuous Subarray Sum LeetCode Solution C++
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { if(nums.size()<2) return false; unordered_map<int, int> mp; mp[0]=-1; int runningSum=0; for(int i=0;i<nums.size();i++) { runningSum+=nums[i]; if(k!=0) runningSum = runningSum%k; if(mp.find(runningSum)!=mp.end()) { if(i-mp[runningSum]>1) return true; } else { mp[runningSum]=i; } } return false; } };
2. Continuous Subarray Sum LeetCode Solution Java
class Solution { public boolean checkSubarraySum(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; sum %= k; if (sum == 0 && i > 0) { return true; } if (map.containsKey(sum) && i - map.get(sum) > 1) { return true; } if (!map.containsKey(sum)) { map.put(sum, i); } } return false; } }
3. Continuous Subarray Sum Solution JavaScript
var checkSubarraySum = function (nums, k) { let sum = 0 let prefix = 0; const hash = new Set(); for (let i = 0; i < nums.length; i++) { sum += nums[i] if (k != 0) sum %= k if(hash.has(sum)) return true hash.add(prefix); prefix = sum; } return false };
4. Continuous Subarray Sum Solution Python
class Solution(object): def checkSubarraySum(self, nums, k): d , s = {0:-1} , 0 for i, n in enumerate(nums): if k != 0: s = (s + n) % k else: s += n if s not in d: d[s] = i else: if i - d[s] >= 2: return True return False