Problem statement
Given an integer array nums and an integer k, return how many contiguous, non-empty subarrays have elements that add up to exactly k.
Values can be negative, so a two-pointer sliding window does not work here.
Examples
- Input
nums = [1, 1, 1], k = 2
- Output
2
Why: [1, 1] at indices 0–1 and at indices 1–2.
- Input
nums = [1, 2, 3], k = 3
- Output
2
Why: [1, 2] and [3].
- Input
nums = [1, -1, 0], k = 0
- Output
3
Why: [1, -1], [0] and [1, -1, 0].
Constraints
- 1 ≤ nums.length ≤ 2 × 10⁴
- −1000 ≤ nums[i] ≤ 1000
- −10⁷ ≤ k ≤ 10⁷
How to answer it out loud
What it tests: Recognizing when a sliding window fails, prefix-sum reasoning, and hash-map counting.
- 1Clarify
Clarify whether values can be negative and whether you need the count or the subarrays themselves.
- 2Implement
Keep a running prefix sum and a map of how often each prefix has appeared; add the count of prefix − k at each step.
- 3Verify
Test a single-element match, all zeros, and negative values; explain O(n) time and O(n) space.
From brute force to the best solution
| Approach | Idea | Time | Space |
|---|---|---|---|
| Every start, running sum | For each start index, extend the end and count sums equal to k. | O(n²) | O(1) |
| Prefix sums + hash mapBest | Count earlier prefix sums equal to prefix − k; each one ends a valid subarray here. | O(n) | O(n) |
The sum of nums[i+1..j] is prefix[j] − prefix[i]. It equals k exactly when prefix[i] = prefix[j] − k, so count how often that earlier prefix has appeared. Seed the map with {0: 1} to count subarrays that start at index 0.
Reference solution
Each version is self-contained and has been run against the examples and test cases on this page.
def subarray_sum(nums: list[int], k: int) -> int: count = prefix = 0 seen = {0: 1} # prefix sum -> times it has occurred for num in nums: prefix += num count += seen.get(prefix - k, 0) # each earlier (prefix - k) ends a match here seen[prefix] = seen.get(prefix, 0) + 1 return count- Time
- O(n)
- Space
- O(n)
- Approach
- Prefix sums + hash map
Edge cases to run before you say “done”
| Input | Expected | Why it matters |
|---|---|---|
| nums = [3], k = 3 | 1 | Needs the {0: 1} seed. |
| nums = [0, 0, 0], k = 0 | 6 | Overlapping zero-sum subarrays all count. |
| nums = [1, -1, 1, -1], k = 0 | 4 | Negative values. |
Answer the main question first, then take these on one at a time:
- Why does a sliding window fail with negative numbers?
- How would you return the longest such subarray?
- What if you need subarrays whose sum is divisible by k?
Check your recording or written solution against this list:
- Using a sliding window with negative values
- Forgetting to seed the map with prefix 0
- Updating the map before counting
This guide combines general interview-practice patterns with the public hiring material below. The practice prompt and coaching are PiriPiri AI editorial content, not official Meta questions or answers.
Official sources reviewed 20 September 2026.