Number of Subarrays with Sum

Medium

Description

Given an integer array nums and an integer goal, return the number of non-empty subarrays with a sum equal to goal.

Examples

Input:nums = [1,0,1,0,1], goal = 2
Output:4
Explanation:

4 subarrays sum to 2.

Input:nums = [1,1,0], goal = 1
Output:2
Explanation:

There are 2 subarrays that sum to 1: [1] (first element) and [1] (second element). The subarray [1,1,0] sums to 2, [1,0] sums to 1, and [0] sums to 0.

Input:nums = [2,1,3,1,2], goal = 3
Output:3
Explanation:

There are 3 subarrays that sum to 3: [3] (single element at index 2), [2,1] (elements at indices 0-1), and [1,2] (elements at indices 3-4).

Constraints

  • 1 ≤ nums.length ≤ 3 × 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!