#K78602. Count Subarrays with Given Sum

    ID: 35123 Type: Default 1000ms 256MiB

Count Subarrays with Given Sum

Count Subarrays with Given Sum

You are given an array of integers and a target integer target. Your task is to count the number of contiguous subarrays whose sum is exactly equal to target.

This problem can be efficiently solved using the prefix sums method along with a hash map (or dictionary) to keep track of cumulative sum frequencies. The key observation is that if the cumulative sum up to index i is sum[i] and you need a subarray that sums to target, then for some previous index j the cumulative sum should satisfy:

\( sum[i] - sum[j] = target \)

which implies that:

\( sum[j] = sum[i] - target \)

Using this fact, count the occurrences and output the total number of subarrays that fulfill the condition.

inputFormat

The input is read from stdin and has the following format:

  1. The first line contains two integers n and target, where n is the number of elements in the array.
  2. The second line contains n space-separated integers representing the array.

outputFormat

Output a single integer to stdout representing the number of contiguous subarrays whose sum is equal to the given target.

## sample
3 2
1 1 1
2

</p>