AceYourInterviews
Checking sign-in…

30. Subarray Sum Equals K

IntermediatePrefix-frequency counting

Count every continuous range of array positions whose values add up exactly to k. Negative values and zeros are permitted, so increasing a range does not necessarily increase its sum.

Two ranges at different positions count as different answers even if their values are identical. Count overlapping ranges separately as well.

Example 1

Input

[1,1,1], k=2

Output

2

Explanation: Intervals [0,1] and [1,2] each sum to two.

Example 2

Input

[0,0], k=0

Output

3

Explanation: Both singletons and the length-two interval count.

Example 3

Input

[1,-1,1], k=1

Output

3

Explanation: The two 1 singletons and the full interval count; shrinking a positive-sum window is not generally valid.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • -1014 <= k <= 1014
Hints
Hint 1

Express a subarray sum as two prefix sums.

Hint 2

Which earlier prefix value would make their difference equal k?

Hint 3

Count earlier occurrences, seed zero once, and query before inserting.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Repeated zero prefixes

[0,0]
0
3