FastPrepSubarray Sum Equals K

Subarray Sum Equals K

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Given an integer array nums and an integer k, return the number of nonempty contiguous subarrays whose sum equals k.

Return the exact count as a signed 64-bit integer.

Function

countSubarraysWithSum(nums: int[], k: int) → long

Examples

Example 1

nums = [1,1,1]k = 2return = 2

The first two and last two elements each sum to 2.

Example 2

nums = [1,2,3]k = 3return = 2

Subarrays [1,2] and [3] qualify.

Example 3

nums = [1,-1,0]k = 0return = 3

[1,-1], [0], and the whole array sum to zero.

Constraints

  • 0 <= nums.length <= 200000.
  • -10^9 <= nums[i], k <= 10^9.

More Google problems

See Google hiring insights
public long countSubarraysWithSum(int[] nums, int k) {
    // Write your code here.
}
nums[1,1,1]
k2
expected2
Checking account…