Continuous Subarray Sum — LeetCode 523 Python Solution

MediumArrayHash TableMathPrefix Sum
Problem
#523
Pattern
Prefix Sum
Reading time
2 min

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

Python
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 False

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview