VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-subarray-sums-ii/

⇱ CSES Solutions - Subarray Sums II - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Subarray Sums II

Last Updated : 23 Jul, 2025

Given an array arr[] of N integers, your task is to count the number of subarrays having sum X.

Examples:

Input: N = 5, X = 7, arr[] = {2, -1, 3, 5, -2}
Output: 2
Explanation: There are 2 subarrays with sum = 7.

  • Subarray {-1, 3, 5}, sum = -1 + 3 + 5 = 7.
  • Subarray {2, -1, 3, 5, 2}, sum = 2 - 1 + 3 + 5 + 2 = 7.

Input: N = 5, X = 3, arr[] = {1, 1, 1, -1, 1}
Output: 2
Explanation: There are 2 subarrays with sum = 3.

  • Subarray {1, 1, 1}, sum = 1 + 1 + 1 = 3.
  • Subarray {1, 1, 1, -1, 1}, sum = 1 + 1 + 1 - 1 + 1 = 3.

Approach: To solve the problem, follow the below idea:

The problem can be solved using Prefix Sums and Map. We can maintain a Map, that stores the prefix sums along with the number of times they have occurred. At each index i, let's say the prefix sum is P, that is sum of subarray arr[0...i] = P. Now if there is an index j (j < i) such that sum of arr[0...j] = P - X, then the sum of subarray arr[j+1...i] will be equal to X. Therefore, for every index i, if we can find the count of prefixes before i which have sum = P - X, we can add the count to our answer and the sum of count for all indices will be the final answer.

This allows us to find a subarray within our current array (by removing a prefix from our current prefix) that sums up to X. Also, as we iterate through the array, we continuously update the map with the new prefix sum after each step so that all possible prefix sums are counted in the map as we traverse the array.

Step-by-step algorithm:

  • Maintain a map, say prefSums to store the count of occurrences of each prefix sum.
  • Maintain a variable pref = 0, to calculate the prefix sum till any index and a variable cnt = 0 to count the number of subarrays with sum = X.
  • Initialize prefSums[0] = 1 so when we get any subarray with sum = X, we can add prefSum[pref - X] = prefSum[0] = 1 to the answer.
  • Iterate over all the elements arr[i],
    • Add arr[i] to prefix sum pref, pref += arr[i].
    • Add the frequency of prefSums[pref - X] to the cnt.
    • Increment the frequency of pref by 1.
  • Return the final answer as cnt.

Below is the implementation of the algorithm:


Output
2

Time Complexity: O(N * logN), where N is the size of array arr[].
Auxiliary Space: O(N)

Comment
Article Tags: