BackhardArrays

Subarray Sum Counter 2 Solution

Problem Statement

Given an array of integers and a target sum, design an algorithm to count the number of subarrays with a sum equal to the target sum. A subarray is a contiguous subset of the array.

Example 1
Input
arr = [1, 2, 3, 4, 5], target_sum = 5
Output
2

Explanation: The subarrays with sum 5 are [2, 3] and [5].

Example 2
Input
arr = [-1, 0, 1, 2, -1, -4], target_sum = 0
Output
2

Explanation: The subarrays with sum 0 are [-1, 0, 1], [-1, -1, 2] and [-1, -4].

Example 3
Input
arr = [0, 0, 0], target_sum = 0
Output
6

Explanation: The subarrays with sum 0 are [0], [0], [0], [0, 0], [0, 0], and [0, 0, 0].

Constraints

  • 1 <= arr.length <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • -10^9 <= target_sum <= 10^9
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free