Skip to content

Subarray Sum Equals K

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.

InputkOutput
[1,1,1]22
[1,2,3]32
  • 1 <= nums.length <= 2×10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
ApproachTimeSpaceBest When
Prefix Sum + Hash MapO(n)O(n)Always — handles negatives too
Brute ForceO(n²)O(1)Understanding only
Section titled “Approach 1: Prefix Sum Hash Map (Recommended)”
★ Recommended

Keep a running prefix sum. Use a hash map count[prefix_sum] → occurrences. For each position, check if prefix_sum - k exists in the map — if it does, there are that many subarrays ending here that sum to k. Add the current prefix sum to the map after checking.

⏱ Time O(n) Single pass 💾 Space O(n) Hash map storage

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

inumprefixprefix−kmap (before check)count addedmap (after insert)
0{}{0:1}
011-1{0:1}0{0:1, 1:1}
1120{0:1, 1:1}1{0:1, 1:1, 2:1}
2131{0:1, 1:1, 2:1}1{0:1, 1:1, 2:1, 3:1}

Result: 2 (subarrays [1,1] at indices 0–1 and 1–2)

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

inumprefixprefix−kmap (before check)count added
0{}
011-2{0:1}0
1230{0:1, 1:1}1
2363{0:1, 1:1, 3:1}1

Result: 2 (subarrays [1,2] and [3])

Animated walkthrough

Prefix sum hash map counting subarrays

Use Next or Autoplay to watch the running prefix sum, the map lookup, and the result accumulate for nums=[1,1,1], k=2.

Step 1 of 4
Waiting to begin...
Array state
Memory / lookup state

function subarraySum(nums, k):
count = {0: 1}
prefix = 0
result = 0
for num in nums:
prefix += num
result += count.get(prefix - k, 0)
count[prefix] = count.get(prefix, 0) + 1
return result
subarray_sum_equals_k_prefix_sum.py
from typing import List
def subarray_sum_prefix_sum(nums: List[int], k: int) -> int:
count = {0: 1}
prefix = 0
result = 0
for num in nums:
prefix += num
result += count.get(prefix - k, 0)
count[prefix] = count.get(prefix, 0) + 1
return result
print(subarray_sum_prefix_sum([1, 1, 1], k=2)) # 2
print(subarray_sum_prefix_sum([1, 2, 3], k=3)) # 2
✓ Simple

Check every possible subarray using two nested loops. The outer loop picks the start index; the inner loop extends the window right, accumulating the sum. When the running sum equals k, increment the count.

⏱ Time O(n²) All subarrays checked 💾 Space O(1) No extra memory

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

ijrunning sum== k?
001no
013yes → count=1
026no
112no
125no
223yes → count=2

Result: 2

function subarraySum(nums, k):
result = 0
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total == k:
result += 1
return result
subarray_sum_equals_k_brute_force.py
from typing import List
def subarray_sum_brute_force(nums: List[int], k: int) -> int:
result = 0
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total == k:
result += 1
return result
print(subarray_sum_brute_force([1, 1, 1], k=2)) # 2
print(subarray_sum_brute_force([1, 2, 3], k=3)) # 2
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
subarray_sum_equals_k_space_optimized.py
"""
Solution for Subarray Sum Equals K
"""
def solve():
"""Implementation for approach 3 of Subarray Sum Equals K"""
pass
if __name__ == "__main__":
print("Solution ready")