FastPrepSubarray Sum Equals K

Subarray Sum Equals K

Apple logoApple● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given an integer array nums and integer k, return how many nonempty contiguous subarrays have sum exactly k. Subarrays with different start or end positions count separately, even when their values are equal.

Values may be negative or zero. An empty input has zero qualifying subarrays.

Function

countSubarrays(nums: int[], k: int) → int

Examples

Example 1

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

The two adjacent length-two subarrays each sum to two.

Example 2

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

The qualifying subarrays are [1,-1], [0], and [1,-1,0].

Constraints

  • 0 <= nums.length <= 20000.
  • -10^9 <= nums[i], k <= 10^9.
  • Use wide arithmetic for running sums; the returned count fits a signed 32-bit integer.

More Apple problems

See Apple hiring insights
public int countSubarrays(int[] nums, int k) {
    // Write your solution here.
}
nums[1,1,1]
k2
expected2
Checking account…