VOOZH about

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

⇱ CSES Solutions - Subarray Sums I - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Subarray Sums I

Last Updated : 23 Jul, 2025

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

Examples:

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

  • Subarray {2, 4, 1}, sum = 2 + 4 + 1 = 7.
  • Subarray {4, 1, 2}, sum = 4 + 1 + 2 = 7.
  • Subarray {7}, sum = 7.

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

  • Subarray {1, 1, 1, 1, 1}, sum = 1 + 1 + 1 + 1 + 1 = 5.
  • Subarray {1, 1, 1, 1, 1}, sum = 1 + 1 + 1 + 1 + 1 = 5.

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

The problem can be solved using Sliding Window Technique. We can use two pointers: start and end to mark the start and end of the sliding window and also maintain the sum of all the elements from start to end. Initially, we set the start and the end to the first element of the array denoting that there is only the first element in the subarray. Now, we increment end pointer till the sum of the window < X. If at any point the sum of the window = X, then we increment the answer by 1 and move start by 1. Otherwise, if at any point the sum of the window > X, then we keep moving start to decrease window sum till it becomes less than or equal to X. If the sum again becomes = X, then increment answer and move start by 1.

At any point, we keep on expanding the sliding window till sum < X and keep on shrinking the window till sum > X.

Step-by-step algorithm:

  • Maintain two pointers, say start = 0 and end = 0 to mark the starting and ending of sliding window.
  • Maintain a variable, say sum = 0 to store the sum of all elements from start to end and a variable cnt = 0 to store the number of subarrays having sum = X.
  • Keep increasing the size of sliding window my moving forward the end pointer till sum < X.
  • Now, if the sum has become greater than X, we decrease the size of sliding window by moving forward the start pointer.
  • After moving the start pointer, if the sum is equal to X, increment cnt by 1.
  • After iterating over all the elements, print cnt as the final answer.

Below is the implementation of the algorithm:


Output
2

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

Comment
Article Tags:
Article Tags: