subarray-sum-equals-k.sh — zsh
arrayshashmapprefix-sum

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

Input / output

  • Input: nums: int[], k: int
  • Output: the count of qualifying subarrays

Examples

  1. nums = [1, 1, 1], k = 2 returns 2.
  2. nums = [1, 2, 3], k = 3 returns 2.
  3. nums = [1, -1, 0], k = 0 returns 3.

Constraints

  • 1 <= nums.length <= 20000
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7

Edge cases

  • Values may be negative or zero, so sliding-window shrinking does not apply.
  • Subarrays that start at index 0 are counted via an initial prefix sum of 0.

Target complexity

  • Aim for O(n) time and O(n) extra space.

Hints

  1. A subarray sum equals prefix[j] - prefix[i]; you want that difference to equal k.
  2. While scanning, count how many earlier prefix sums equal current - k.

Follow-up Why does the negative-number case rule out the classic shrinking sliding-window approach?

Examples
Example 1
Input: nums = [1,1,1], k = 2
Output: 2
Example 2
Input: nums = [1,2,3], k = 3
Output: 2
Example 3
Input: nums = [1,-1,0], k = 0
Output: 3
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.