-
-
Notifications
You must be signed in to change notification settings - Fork 155
Adding the Solution of a problem 523 #917
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 2 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
0446c8e
add all
parikhitritgithub 3b7da28
add all
parikhitritgithub 3084618
Update 523. Continuous Subarray Sum.md
parikhitritgithub 7c0058f
Update 523. Continuous Subarray Sum.md
parikhitritgithub 0fd8d17
Update 523. Continuous Subarray Sum.md
parikhitritgithub 25b357b
Update 523. Continuous Subarray Sum.md
parikhitritgithub d0d2c61
Update 523. Continuous Subarray Sum.md
parikhitritgithub af80b7e
Update 523. Continuous Subarray Sum.md
parikhitritgithub fa505b9
Update 523. Continuous Subarray Sum.md
parikhitritgithub cea31af
Update 523. Continuous Subarray Sum.md
parikhitritgithub aaeb70f
Update 523. Continuous Subarray Sum.md
parikhitritgithub File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
200 changes: 200 additions & 0 deletions
200
dsa-solutions/lc-solutions/0500-0599/523. Continuous Subarray Sum.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,200 @@ | ||
--- | ||
id: Continuous Subarray Sum | ||
title: Continuous Subarray Sum | ||
sidebar_label: 0523 Continuous Subarray Sum | ||
tags: | ||
- prefix sum + hashmap | ||
- LeetCode | ||
- Java | ||
- Python | ||
- C++ | ||
description: "This is a solution to the Continuous Subarray Sum problem on LeetCode." | ||
--- | ||
|
||
## Problem Description | ||
|
||
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 of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. | ||
|
||
### Examples | ||
|
||
**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: root = 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 | ||
``` | ||
|
||
|
||
### Constraints | ||
|
||
- 1 <= nums.length <= 105 | ||
- 0 <= nums[i] <= 109 | ||
- 0 <= sum(nums[i]) <= 231 - 1 | ||
- 1 <= k <= 231 - 1 | ||
|
||
|
||
--- | ||
|
||
## Solution for Continuous Subarray Sum Problem | ||
|
||
### Intuition | ||
This is a prefix sum's problem. Due to LC | ||
|
||
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. | ||
|
||
modulo k there are 0,1,...k-1 totally k possible for prefix sum (mod k). | ||
For this constraint 1 <= nums.length <= 10^5 an O(n^2) solution may lead to TLE. | ||
For this constraint 1 <= k <= 2^31 - 1, an array version solution might lead to MLE. | ||
|
||
A hash map with care on prefix sum mod k to use is however a tip. The array version is used when k<n combining the hash map version; that will be the faster than other solutions. | ||
|
||
Thanks to the comments of @Sergei proposing to use unordered_set, a combination of bitset with unordered_set is implemented which outperforms all other solutions with the elapsed time 86ms & beats 99.75% | ||
|
||
|
||
### Approach | ||
|
||
|
||
- First try uses array version for mod_k(k), but LC's constraints: 1 <= k <= 2^31 - 1 which leads to MLE. | ||
- 2nd approach uses unordered_map<int, vector<int>> instead of an array which is accepted by LC. | ||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- Since the computation uses mod_k[prefix].front(), a simple hash table unordered_map<int, int> mod_k is sufficient for this need. | ||
ajay-dhangar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- An acceptable version using array version when k<n otherwise hash map which is a combination of both different data structures. | ||
- Let prefix denote the current prefix sum modulo k. The very crucial part is the following: | ||
|
||
|
||
|
||
|
||
#### Code in Different Languages | ||
|
||
<Tabs> | ||
<TabItem value="Python" label="Python"> | ||
<SolutionAuthor name="@parikhitkurmi"/> | ||
```python | ||
|
||
class Solution: | ||
def checkSubarraySum(self, nums: List[int], k: int) -> bool: | ||
n=len(nums) | ||
if n<2: return False | ||
mod_k={} | ||
prefix=0 | ||
mod_k[0]=-1 | ||
for i, x in enumerate(nums): | ||
prefix+=x | ||
prefix%=k | ||
if prefix in mod_k: | ||
if i>mod_k[prefix]+1: | ||
return True | ||
else: | ||
mod_k[prefix]=i | ||
return False | ||
|
||
|
||
|
||
|
||
``` | ||
|
||
</TabItem> | ||
<TabItem value="Java" label="Java"> | ||
<SolutionAuthor name="@parikhitkurmi"/> | ||
|
||
```java | ||
|
||
class Solution { | ||
public boolean checkSubarraySum(int[] nums, int k) { | ||
int n = nums.length, prefSum = 0; | ||
Map<Integer, Integer> firstOcc = new HashMap<>(); | ||
firstOcc.put(0, 0); | ||
|
||
for (int i = 0; i < n; i++) { | ||
prefSum = (prefSum + nums[i]) % k; | ||
if (firstOcc.containsKey(prefSum)) { | ||
if (i + 1 - firstOcc.get(prefSum) >= 2) { | ||
return true; | ||
} | ||
} else { | ||
firstOcc.put(prefSum, i + 1); | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
} | ||
|
||
``` | ||
|
||
</TabItem> | ||
<TabItem value="C++" label="C++"> | ||
<SolutionAuthor name="@parikhitkurmi"/> | ||
```cpp | ||
|
||
class Solution { | ||
public: | ||
bool checkSubarraySum(vector<int>& nums, int k) { | ||
map<int , int> mp ; | ||
mp[0] = 0 ; | ||
int sum = 0 ; | ||
for(int i = 0 ; i< nums.size() ; i++ ) { | ||
sum += nums[i] ; | ||
int rem = sum%k ; | ||
|
||
if(mp.find(rem)==mp.end()){ | ||
mp[rem] = i+1 ; | ||
|
||
}else if (mp[rem] < i ) { | ||
return true ; | ||
|
||
} | ||
|
||
|
||
} | ||
return false ; | ||
|
||
} | ||
}; | ||
|
||
|
||
``` | ||
|
||
</TabItem> | ||
</Tabs> | ||
|
||
|
||
|
||
|
||
|
||
## References | ||
|
||
- **LeetCode Problem:** [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) | ||
- **Solution Link:** [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/submissions/1281964300/) | ||
- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) | ||
- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.