Article start
DSA Course: Interview Patterns and Problem Solving
Module 9: Hashing & Prefix Sum

Subarray Sum Equals K: Prefix Sum Hashmap Pattern

Count target-sum subarrays using prefix sum frequencies.

May 29, 2026·25

Learning Outcome

After this lesson, you should be able to convert subarray sum questions into prefix sum difference lookups.

Problem Statement

Given nums and k, return the number of continuous subarrays whose sum equals k.

InputOutputWhy
nums = [1,1,1], k = 22The subarrays at indexes 0..1 and 1..2 both sum to 2.

Brute Force Approach

Check every start and end index and compute each subarray sum. This is quadratic.

Optimized Approach

Maintain a running prefix sum. If currentSum - k appeared before, each occurrence forms a valid subarray ending here.

Exact Pseudocode

freq[0] = 1
sum = 0
answer = 0
for x in nums:
  sum += x
  answer += freq[sum - k]
  freq[sum] += 1
return answer

Reference Code

from collections import defaultdict

class Solution:
    def subarraySum(self, nums, k):
        freq = defaultdict(int)
        freq[0] = 1
        total = 0
        answer = 0

        for x in nums:
            total += x
            answer += freq[total - k]
            freq[total] += 1

        return answer

Sample Dry Run

StepStateResult
Startfreq[0] = 1Subarrays from index 0 are counted
First 1sum = 1, need -1answer = 0
Second 1sum = 2, need 0answer = 1
Third 1sum = 3, need 1answer = 2

Complexity

MeasureValueReason
TimeO(n)Each number updates the running sum and hash map once.
SpaceO(n)The map can store many distinct prefix sums.

Edge Cases

  • Negative numbers make sliding window unreliable.
  • freq[0] is required for subarrays starting at index 0.
  • Multiple equal prefix sums must be counted, not just stored as true or false.

Interview Checklist

  • Use prefix sum difference currentSum - k.
  • Add existing frequency before incrementing current sum frequency.
  • Store counts, not just a set.

FAQs

Why does currentSum - k matter?

If an earlier prefix equals currentSum - k, the subarray after that prefix sums to k.

Why not use sliding window?

Sliding window fails when negative numbers can shrink or grow sums unpredictably.

What is the core pattern?

Prefix sum with hash map frequency.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.