Problem · Array

Count Subarrays With Target Sum

Learn this problem
MediumAmazon logoAmazonFULLTIMEPHONE SCREEN
See Amazon hiring insights

Problem statement

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

A subarray is a contiguous range of one or more elements. Different index ranges count separately, even when they contain the same values.

Function

countSubarraysWithTargetSum(nums: int[], target: long) → long

Examples

Example 1

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

The subarrays at indices 0 through 1 and 1 through 2 each sum to 2.

Example 2

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

The ranges [1, -1], [1, -1, 0], and [0] have sum 0.

Constraints

  • 1 <= nums.length <= 100000
  • -10^9 <= nums[i] <= 10^9
  • -10^14 <= target <= 10^14
  • The answer fits in a signed 64-bit integer.

More Amazon problems

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