noodleProblems/
Subarray Sum Equals K
#127

Subarray Sum Equals K

AlgorithmmediumArrayHash TablePrefix Sum

Given an integer array nums and an integer k, return the **total number of contiguous subarrays** whose elements sum to exactly k.

The array may contain negative numbers and zeros, so you can't rely on a sliding window — a longer subarray isn't guaranteed to have a larger sum.

Example cases

  • two subarrays
    in nums = [1,1,1], k = 2
    out 2
    [1,1] at indices 0..1 and 1..2.
  • single hit
    in nums = [1,2,3], k = 3
    out 2
    [3] and [1,2] both sum to 3.
  • with negatives
    in nums = [1,-1,0], k = 0
    out 3
    [1,-1], [0], and [1,-1,0] all sum to 0.
  • no subarray
    in nums = [1,2,3], k = 7
    out 0

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
Saved
nums =
[1,1,1]
k =
2