Neural Mastery
← Practice
Subarray Sum Equals Kmedium

Subarray Sum Equals K

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement Subarray Sum Equals K via the prefix-sum-plus-hash-map trick -- the technique that makes this solvable in O(n) even with negative numbers present, where a sliding window would fail.

Related Skills

Task

Implement subarray_sum(nums, k): track a running prefix sum and a hash map of "how many times has each prefix sum value occurred so far." A subarray ending at the current position sums to k exactly when (current prefix sum - k) has occurred before -- add that count to the running total.

Function Signature

subarray_sum(nums: list[int], k: int) -> int

Examples

Example 1: Two Matching Subarrays
Input: nums = [1, 1, 1] k = 2
Output: 2
Explanation: [1,1] at indices 0-1 and 1-2
Example 2: Two Different-Length Matches
Input: nums = [1, 2, 3] k = 3
Output: 2
Explanation: [1,2] and [3]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • nums may contain negative numbers -- a sliding-window approach (which requires monotonic growth) is not valid here.
  • Initialize the prefix-sum-count map with {0: 1} to correctly count subarrays that start at index 0.
Python3Saved ✓
def subarray_sum(nums: list[int], k: int) -> int:
"""Return the number of CONTIGUOUS subarrays of nums whose elements
sum to exactly k. nums may contain negative numbers (so a sliding
window alone does not work here -- use prefix sums)."""
# Your implementation here
pass

Case 1: Two Matching Subarrays
Input: nums = [1, 1, 1] k = 2
Expected: 2
Case 2: Two Different-Length Matches
Input: nums = [1, 2, 3] k = 3
Expected: 2