Skip to content

Commit 0ac3b0e

Browse files
authored
Create continuous-subarray-sum.py
1 parent f28a3c6 commit 0ac3b0e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Python/continuous-subarray-sum.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Time: O(n)
2+
# Space: O(k)
3+
4+
# Given a list of non-negative numbers and a target integer k,
5+
# write a function to check if the array has a continuous subarray
6+
# of size at least 2 that sums up to the multiple of k, that is,
7+
# sums up to n*k where n is also an integer.
8+
#
9+
# Example 1:
10+
# Input: [23, 2, 4, 6, 7], k=6
11+
# Output: True
12+
# Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
13+
# Example 2:
14+
# Input: [23, 2, 6, 4, 7], k=6
15+
# Output: True
16+
# Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.
17+
# Note:
18+
# The length of the array won't exceed 10,000.
19+
# You may assume the sum of all the numbers is in the range of a signed 32-bit integer.
20+
21+
class Solution(object):
22+
def checkSubarraySum(self, nums, k):
23+
"""
24+
:type nums: List[int]
25+
:type k: int
26+
:rtype: bool
27+
"""
28+
count = 0
29+
lookup = {0: -1}
30+
for i, num in enumerate(nums):
31+
count += num
32+
if k:
33+
count %= k
34+
if count in lookup:
35+
if i - lookup[count] > 1:
36+
return True
37+
else:
38+
lookup[count] = i
39+
40+
return False

0 commit comments

Comments
 (0)