DSAPrefix + HashCount

Subarray Sum Equals K Visualizer

What is Subarray Sum Equals K

A subarray sum from i+1 to j is prefix[j] − prefix[i]. That equals k exactly when a previous prefix prefix[j] − k exists. A hash map stores how many times each prefix has appeared.

  • Seed {0: 1} so a prefix that itself equals k counts as a subarray from the start.
  • Query then insert the current prefix, same as the pair-count pattern.
  • Negatives are fine — hashing does not need a sliding window’s monotonicity.

How this visualizer works

Array 1, 2, 3, k = 3. Prefixes 1, 3, 6 produce two subarrays: [1,2] and [3].

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def subarraySum(arr, k):
2freq, pref, ans = {0: 1}, 0, 0
3for x in arr:
4pref += x
5ans += freq.get(pref - k, 0)
6freq[pref] = freq.get(pref,0)+1
7return ans

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def subarraySum(arr, k):
2freq, pref, ans = {0: 1}, 0, 0
3for x in arr:
4pref += x
5ans += freq.get(pref - k, 0)
6freq[pref] = freq.get(pref,0)+1
7return ans

complexity.md

OperationTime
Each prefixO(1) expected
Full scanO(n)
SpaceO(n)

Python implementation

solution.py

1def subarraySum(arr, k):
2 freq, pref, ans = {0: 1}, 0, 0
3 for x in arr:
4 pref += x
5 ans += freq.get(pref - k, 0)
6 freq[pref] = freq.get(pref, 0) + 1
7 return ans