> For the complete documentation index, see [llms.txt](https://joshualbarb.gitbook.io/leetcode-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joshualbarb.gitbook.io/leetcode-problems/hash-table/subarray-sum-equals-k.md).

# Subarray Sum Equals K

## Problem

Given an array of integers `nums` and an integer `k`, return *the total number of continuous subarrays whose sum equals to `k`*.

{% hint style="info" %}
For example:

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

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

{% endhint %}

## Solution

```
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        sumMap = {}
        count = 0
        sums = 0
        
        for i in range(len(nums)):
            sums+=nums[i]
            if sums == k:
                count+=1
            if sums-k in sumMap: #checking hash map to see is sum exists
                count+=sumMap[sums-k]
            if sums in sumMap:
                sumMap[sums]+=1
            else:
                sumMap[sums] = 1
        return count
        
#Calculating the prefix sums to i and storing it in 
#a hash map

#If currSum - k exists in hash map, then this means we
#have a subarray that is equal to k, so we can increase
#the count

#Time: O(n)
#Space: O(n)
```
