Subarray Sum Equals K

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write countSubarrays(nums, k): return how many contiguous runs of one or more numbers in nums add up to exactly k. The numbers can be negative or zero, and nums should be left unchanged; an empty list gives 0. For example, countSubarrays([1, 2, 3], 3) is 2: the runs [1, 2] and [3]. The checks include 100,000 numbers, so adding up every possible run is too slow.

Your code must pass

  • Counts the runs that add up to k, leaving nums unchanged
  • Handles negative numbers and zeros
  • Returns 0 when nothing adds up
  • Is fast enough for 100,000 numbers