ntree.ai
ntree.aiSubarray Sum Equals K

Subarray Sum Equals K

mediumsolvedattempted

Given an array of integers nums and an integer k, return the number of contiguous subarrays whose elements add up to k.

Example 1:

Input:  nums = [3, 4, 7, 2, -3, 1], k = 7
Output: 3
Explanation: [3, 4], [7] and [7, 2, -3, 1] add up to 7.

Example 2:

Input:  nums = [1, 2, 3], k = 3
Output: 2
Explanation: [1, 2] and [3].

Constraints:

  • 1 <= length of nums <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
def subarraySum(nums: list[int], k: int) -> int:
pass
 

Press Visualise to step through your code.