Continuous Subarray Sum — LeetCode 523 Python Solution
- Problem
- #523
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
d = {0: -1}
s = 0
for i, x in enumerate(nums):
s = (s + x) % k
if s not in d:
d[s] = i
elif i - d[s] > 1:
return True
return FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the array \textit{nums} auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 523. Continuous Subarray Sum is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 523. Continuous Subarray Sum?
- LeetCode 523. Continuous Subarray Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 523. Continuous Subarray Sum?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 523. Continuous Subarray Sum?
- The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
- What topics does LeetCode 523. Continuous Subarray Sum cover?
- LeetCode 523. Continuous Subarray Sum is tagged Array, Hash Table, Math and Prefix Sum on LeetCode.