> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Subarray Sum Equals K Python Solution

> Tested Python solution for LeetCode 560 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 560, Medium. Topics: Array, Hash Table, Prefix Sum. [View on LeetCode](https://leetcode.com/problems/subarray-sum-equals-k/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 560   # by problem number
lcpy gen -s subarray_sum_equals_k   # by problem name
```

## 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.

### Examples

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

```
Input: nums = [1,2,3], k = 3
Output: 2
```

### Constraints

* 1 \<= nums.length \<= 2 \* 10^4
* -1000 \<= nums\[i] \<= 1000
* -10^7 \<= k \<= 10^7

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subarray_sum_equals_k/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subarray_sum_equals_k/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import defaultdict


class Solution:
    # Time: O(n)
    # Space: O(n)
    def subarray_sum(self, nums: list[int], k: int) -> int:
        prefix_sum_counts = defaultdict(int)
        prefix_sum_counts[0] = 1
        current_sum = 0
        count = 0

        for num in nums:
            current_sum += num
            if current_sum - k in prefix_sum_counts:
                count += prefix_sum_counts[current_sum - k]
            prefix_sum_counts[current_sum] += 1

        return count
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(n)  |

## Tags

[Grind](/catalog/grind), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
