Example 1
- Input
- nums = [1, 1, 1], k = 2
- Output
- 2
The subarrays nums[0..1] and nums[1..2] each sum to 2.
Given an integer array and a target k, count how many contiguous non-empty subarrays sum exactly to k. Negative values are allowed, so the window cannot simply grow and shrink.
Given an integer array nums and an integer k, return the number of contiguous, non-empty subarrays whose elements sum to k. A subarray consists of adjacent indices; it cannot skip a position.
Count occurrences by their start and end indices, including overlapping subarrays. Negative values and zeros are allowed, so moving an endpoint does not necessarily increase or decrease the sum.
1 <= nums.length <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7The subarrays nums[0..1] and nums[1..2] each sum to 2.
The subarrays [1, 2] at indices 0..1 and [3] at index 2 each sum to 3.
All three length-one subarrays, both length-two subarrays, and the whole length-three array sum to zero: 3 + 2 + 1 = 6. The empty subarray is not counted.
The single elements at indices 0 and 2 each sum to one, and the entire array also sums to one. Repeated prefix totals represent different start boundaries.
The only non-empty subarray sums to two. A zero-length interval must not be counted when k is zero.
A prefix sum is the total before a boundary in the array. Subtracting two boundary totals leaves exactly the values between them. For [1, 1, 1], the boundary totals are [0, 1, 2, 3]; differences 2 - 0 and 3 - 1 each give k = 2. At a current total P, every earlier boundary with total P - k starts a matching subarray. A frequency map counts those earlier boundaries, even when several share the same total.
Reveal Brute Force: intuition, complexity, and code
{0: 1}. Add the frequency of P - k to the answer before inserting the current P.[2] with k = 2 returns 1; with k = 0 it returns 0. Empty arrays are outside the constraints.[0, 0, 0] with k = 0 returns 6, since every non-empty interval qualifies. At the maximum length of 20000, the count is 200010000.[1, -1, 1] with k = 1 returns 3; the same prefix total can appear at several different boundaries.[1, 1, 1] with k = 3, relies on the initial prefix frequency {0: 1}.[-1, -1, 1] with k = -1 has three matching subarrays. Large targets with no match must return zero.{0: 1} loses intervals beginning at index 0; adding a separate whole-prefix check while keeping the seed double-counts those intervals.current - earlier = k, then explain why the map holds only earlier prefixes and why it stores counts. The optimization improves quadratic time to expected linear time while adding O(n) storage.For contiguous-sum counting, a prefix difference turns each ending position into a search for earlier totals. A hash map of frequencies counts every valid start, including repeated prefix values, while lookup-before-insertion keeps intervals non-empty.