Count the subarrays that add up to k
Coding problemMediumAsked in: Adobe, Amazon, Apple, Google, Meta, Microsoft
Given a list of integers and a number k, count the runs of one or more neighbouring values (subarrays) whose sum is exactly k.
Values can be negative or zero, so runs can overlap and a sum can return to k more than once. The count can exceed two billion, so return it as a 64-bit integer.
Examples
Example 1
Input: nums = [1,1,1], k = 2
Output: 2
Example 2
Input: nums = [1,2,3], k = 3
Output: 2
The runs [1, 2] and [3].
Example 3
Input: nums = [0,0,0], k = 0
Output: 6
Constraints
- The list holds between 1 and 100,000 integers
- Each value is between -1,000 and 1,000
- k is between -10,000,000 and 10,000,000
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.