Skip to main content

523. Continuous Subarray Sum

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

Python

class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
if k <= 0:
return

# key: sum mod k, value: index
prefix_map = {0: -1}
remainder = 0

for i, num in enumerate(nums):
remainder += num
remainder %= k

if remainder in prefix_map:
if i - prefix_map.get(remainder) > 1:
return True
else:
prefix_map[remainder] = i

return False