dsa · medium

Subarray Sum Equals K

You are given an integer array nums and an integer k. Count the subarrays (contiguous, non-empty) whose elements sum to exactly k. Two subarrays are different if they start or end at different indices, even when their values match.

Arguments

Example

nums = [1,1,1], k = 2

The subarrays [1,1] (indices 0-1) and [1,1] (indices 1-2) both sum to 2, so the answer is 2.

nums = [1,-1,0], k = 0

[1,-1], [1,-1,0], and [0] all sum to 0 → 3.

Constraints

1 <= nums.length <= 2 * 10^4 -1000 <= nums[i] <= 1000 -10^7 <= k <= 10^7 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[1,1,1]
2

Expected:
2

Example 2

Input:
[1,2,3]
3

Expected:
2

Example 3

Input:
[1,-1,0]
0

Expected:
3

Open in the Dojo editor