Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dc8a236

Browse files
committed
O(n) time and O(n) space using hashmap.
1 parent 29a10ba commit dc8a236

File tree

1 file changed

+8
-16
lines changed

1 file changed

+8
-16
lines changed

‎523. Continuous Subarray Sum/523. Continuous Subarray Sum.py‎

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,12 @@
2222
"""
2323
class Solution:
2424
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
25-
"""
26-
The idea here is if two sums have the same module and they are atleast two indexes apart then we can return true otherwise false.
27-
For [0,2], k=2 prefix sum would be [0,2] and sum2 = 2 and sum1 = 0. sum2 - sum1 can be divided by k and the distance between those two indexes is atleast 2.
28-
"""
29-
hmap = {0:-1} # initially at index -1 the sum would be zero.
30-
for i in range(1,len(nums)):
31-
nums[i] += nums[i-1] # prefix sum
32-
for i in range(len(nums)):
33-
temp = nums[i]
34-
if k:
35-
temp %= k
36-
if temp in hmap.keys():
37-
if i - hmap[temp] >= 2:
38-
return True
25+
hmap,total = {},0
26+
for i,num in enumerate(nums):
27+
total = (total + num) % k
28+
if total == 0 and i > 0: return True # if total % k =0 that means we have a multiple of k present already and check if the array size is greater than or equal to 2.
29+
if total not in hmap:
30+
hmap[total] = i
3931
else:
40-
hmap[temp] =i
41-
return False
32+
ifi-hmap[total] >=2: returnTrue
33+
return False

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /