Menu
CoddyTech

Subarray Sum Equals K

You get an array of integers nums and an integer k. Count the subarrays whose elements add up to exactly k. A subarray is a run of one or more neighbouring elements. Two subarrays count separately when they start or end at different positions, even if they hold the same values. The values may be negative or zero.

Function

subarraySum(nums: integer-array, k: integer) → integer
numsinteger-array
the array of integers, which may hold negative values and zeros
kinteger
the sum a subarray must reach to be counted
Returnsinteger
the number of subarrays whose elements add up to k

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • -1000 ≤ nums[i] ≤ 1000
  • -107 ≤ k ≤ 107
  • An array this long has at most 200,010,000 subarrays, so the answer fits in a 32-bit signed integer.

Examples

Input
nums = [3, 4, -7, 1, 3, 3, 1, -4]k = 7
Output
4
Explanation
Four runs add up to 7: [3, 4], [1, 3, 3], [3, 3, 1] and [3, 4, -7, 1, 3, 3]. In the last one the -7 cancels the 3 and the 4, and the sum climbs back to 7 later, so a run can match even after its sum has passed k.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

How would you change the solution to return the length of the longest subarray that adds up to k, still in O(n) time?

Reset code
def subarraySum(nums, k):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [3, 4, -7, 1, 3, 3, 1, -4]
k = 7

Expected

4