Problem · Array

Count Subarrays with Sum K

Learn this problem
MediumByteDance logoByteDanceFULLTIMEPHONE SCREEN

Problem statement

Given an integer array numbers and an integer target, return the number of non-empty contiguous subarrays whose elements sum to target.

Subarrays with the same values at different positions count separately.

Function

countSubarraysWithSum(numbers: int[], target: int) → int

Examples

Example 1

numbers = [1,1,1]target = 2return = 2

The qualifying subarrays occupy indices [0,1] and [1,2].

Example 2

numbers = [1,-1,0]target = 0return = 3

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

Constraints

  • 1 <= numbers.length <= 100000
  • -10000 <= numbers[i] <= 10000
  • -10^9 <= target <= 10^9
  • The answer fits in a signed 32-bit integer.

More ByteDance problems

drafts saved locally
public int countSubarraysWithSum(int[] numbers, int target) {
    // Write your code here.
}
numbers[1,1,1]
target2
expected2
checking account