You are given an array of whole numbers, nums, and a number k. A subarray is a run of one or more neighbouring elements.
Count how many subarrays add up to exactly k. Two subarrays at different positions count separately, even if they hold the same values.
Example 1
Input: nums = [2, 1, -1, 3], k = 3 Output: 3 Why: [2, 1], [1, -1, 3] and [3]
2 more examples and the constraints
Example 2
Input: nums = [4, 4, 4, 4], k = 8 Output: 3 Why: each pair of neighbours makes 8
Example 3
Input: nums = [1, -1, 1, -1], k = 0 Output: 4 Why: three pairs and the whole array sum to 0
Constraints
- 1 ≤ length of nums ≤ 20,000
- −1,000 ≤ each number ≤ 1,000
- −10,000,000 ≤ k ≤ 10,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every start, every endO(n²)
- Prefix sums + hash mapO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 numbers | Verdict |
|---|---|---|---|
| Every start, every end | O(n²) | Mention it, then move on | |
| Prefix sums + hash map | O(n) | Best; one pass |
n = length of nums.
Edge cases to test
- Negative numbers. [2, 1, −1, 3] with k = 3: a window that grows can shrink in sum, so two pointers fail.
- k = 0 with zeros. [0, 0, 0] has 6 runs that sum to 0: every run counts.
- Run from index 0. [5] with k = 5 is counted only because the map starts with {0: 1}.
- No match. [1, 2, 3] with k = 100 returns 0.
Common mistakes
- Forgetting the {0: 1} seed, which misses every run that starts at index 0.
- Storing the current prefix before the lookup, which counts an empty run when k = 0.
- Using a sliding window, which only works when every number is positive.
How to talk through it
- 1Clarify. Can numbers be negative? Can k be 0 or negative? Do equal runs at different positions count twice?
- 2Give the brute force. Every start with a running total: O(n²), about 200 million steps at the limit.
- 3Rewrite the sum. A run sums to k when prefix now minus an earlier prefix is k. Count earlier prefixes equal to prefix − k.
- 4Code the map. Seed it with {0: 1}, look up before storing, and say why both matter.
- 5Test out loud. Run [5] with k = 5, [0, 0, 0] with k = 0 and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?