#K39517. Count Subarrays with Given Sum
Count Subarrays with Given Sum
Count Subarrays with Given Sum
You are given an array of integers of length N and an integer X. Your task is to count the number of contiguous subarrays whose sum is exactly X. A subarray is defined as a contiguous segment of the array.
Mathematically, given an array a₁, a₂, …, aₙ, count the number of pairs (i, j) with 1 ≤ i ≤ j ≤ N such that ( \sum_{k=i}^{j} a_k = X ).
This problem can be efficiently solved using cumulative sums and a frequency map to store previously seen sums. The intended solution runs in O(N) time.
inputFormat
The input is provided via standard input. The first line contains two space-separated integers: N (the size of the array) and X (the target sum). The second line contains N space-separated integers representing the array elements.
outputFormat
Output a single integer representing the number of subarrays whose sum equals X, printed to standard output.## sample
5 9
1 2 3 4 5
2