Subarray Sum Equals K — LeetCode 560 Python Solution

MediumArrayHash TablePrefix Sum
Problem
#560
Pattern
Prefix Sum
Reading time
2 min

The problem

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.

Example

Input
nums = [1,1,1], k = 2
Output
2

Python solution

Python
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        cnt = Counter({0: 1})
        ans = s = 0
        for x in nums:
            s += x
            ans += cnt[s - k]
            cnt[s] += 1
        return ans

Complexity

MeasureComplexity
Time`O(n)`
Space`O(n)` auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 560. Subarray Sum Equals K 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 560. Subarray Sum Equals K?
LeetCode 560. Subarray Sum Equals K is rated Medium on LeetCode.
What is the time complexity of LeetCode 560. Subarray Sum Equals K?
The Python solution on this page runs in `O(n)`.
What is the space complexity of LeetCode 560. Subarray Sum Equals K?
The Python solution on this page uses `O(n)` auxiliary space.
What topics does LeetCode 560. Subarray Sum Equals K cover?
LeetCode 560. Subarray Sum Equals K is tagged Array, Hash Table 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