Problem · Array

Count Subarrays with a Target Sum

Learn this problem
MediumMeta logoMetaFULLTIMEPHONE SCREEN
See Meta hiring insights

Problem statement

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

The array may be empty and may contain positive, zero, and negative values. Return 0 when no qualifying subarray exists.

Function

subarraySum(nums: int[], target: int) → int

Examples

Example 1

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

The subarrays at indices [0,1] and [1,2] both sum to 2.

Example 2

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

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

Example 3

nums = []target = 5return = 0

An empty array has no non-empty subarrays.

Constraints

  • Every element and target fit in a signed 32-bit integer.
  • Prefix sums are accumulated with a signed 64-bit integer.
  • The returned count fits in a signed 32-bit integer.

More Meta problems

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