Open In App

CSES Solutions – Subarray Sums I

Last Updated : 28 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;

// Function to count the number of subarray with sum = X
ll solve(ll N, ll X, vector<ll>& arr)
{
    // Two pointers to mark the starting and ending of
    // sliding window
    ll start = 0, end = -1;
    // Variable to store sum of all elements in the current
    // sliding window
    ll sum = 0;
    // Variable to store the count of subarrays with sum = X
    ll cnt = 0;

    while (end < N) {
        // Increase the size of sliding window by moving the
        // end till the sum is smaller than X
        while (end < N && sum < X) {
            end += 1;
            sum += arr[end];
        }
        // Decrease the size of sliding window by moving the
        // start till the sum is greater than X
        while (start <= end && sum > X) {
            sum -= arr[start];
            start += 1;
        }

        // If the sum is equal to X, increase the count by 1
        if (sum == X) {
            cnt += 1;
            sum -= arr[start];
            start += 1;
        }
    }
    return cnt;
}

int main()
{
    // Sample Input
    ll N = 6, X = 5;
    vector<ll> arr = { 1, 1, 1, 1, 1, 1 };

    cout << solve(N, X, arr);
}
Java
import java.util.*;

public class SubarrayWithSumX {
    // Function to count the number of subarrays with sum = X
    static long solve(int N, int X, List<Integer> arr) {
        // Two pointers to mark the starting and ending of the sliding window
        int start = 0, end = 0;
        // Variable to store sum of all elements in the current sliding window
        long sum = 0;
        // Variable to store the count of subarrays with sum = X
        long cnt = 0;

        while (end < N) {
            // Increase the size of the sliding window by moving the end until the sum is smaller than X
            sum += arr.get(end);
            end += 1;

            // Decrease the size of the sliding window by moving the start until the sum is greater than X
            while (start < end && sum > X) {
                sum -= arr.get(start);
                start += 1;
            }

            // If the sum is equal to X, increase the count by 1
            if (sum == X) {
                cnt += 1;
            }
        }
        return cnt;
    }

    public static void main(String[] args) {
        // Sample Input
        int N = 6, X = 5;
        List<Integer> arr = Arrays.asList(1, 1, 1, 1, 1, 1);

        System.out.println(solve(N, X, arr));
    }
}


// This code is contributed by shivamgupta310570
C#
using System;

class Program
{
    static int Solve(int N, int X, int[] arr)
    {
        // Two pointers to mark the starting and ending of
        // sliding window
        int start = 0;
        int end = 0;
        // Variable to store sum of all elements in the current
        // sliding window
        int sumVal = 0;
        // Variable to store the count of subarrays with sum = X
        int cnt = 0;

        while (end < N)
        {
            // Increase the size of sliding window by moving the
            // end till the sum is smaller than X
            sumVal += arr[end];
            while (start <= end && sumVal > X)
            {
                // Decrease the size of sliding window by moving the
                // start till the sum is greater than X
                sumVal -= arr[start];
                start += 1;
            }

            // If the sum is equal to X, increase the count by 1
            if (sumVal == X)
            {
                cnt += 1;
                // Move the start pointer to the right
                if (start <= end)
                {
                    sumVal -= arr[start];
                    start += 1;
                }
            }

            // Move the end pointer to the right
            end += 1;
        }

        return cnt;
    }

    static void Main()
    {
        // Sample Input
        int N = 6;
        int X = 5;
        int[] arr = { 1, 1, 1, 1, 1, 1 };

        Console.WriteLine(Solve(N, X, arr));
    }
}
JavaScript
function GFG(N, X, arr) {
    // Two pointers to mark the starting and ending of
    // sliding window
    let start = 0;
    let end = 0;
    let sum = 0;
    // Variable to store the count of the subarrays with sum = X
    let cnt = 0;
    while (end < N) {
        // Increase the size of the sliding window by moving the
        // end till the sum is smaller than X
        sum += arr[end];
        while (start <= end && sum > X) {
            sum -= arr[start];
            start++;
        }
        // If the sum is equal to X and increase the count by 1
        if (sum == X) {
            cnt++;
            // Move the start pointer to the right
            sum -= arr[start];
            start++;
        }
        // Move the end pointer to the right
        end++;
    }

    return cnt;
}
// Input
let N = 6;
let X = 5;
let arr = [1, 1, 1, 1, 1, 1];
console.log(GFG(N, X, arr));
Python3
# Function to count the number of subarrays with sum = X
def solve(N, X, arr):
    # Two pointers to mark the starting and ending of
    # sliding window
    start = 0
    end = 0
    # Variable to store sum of all elements in the current
    # sliding window
    sum_val = 0
    # Variable to store the count of subarrays with sum = X
    cnt = 0

    while end < N:
        # Increase the size of sliding window by moving the
        # end till the sum is smaller than X
        sum_val += arr[end]
        while start <= end and sum_val > X:
            # Decrease the size of sliding window by moving the
            # start till the sum is greater than X
            sum_val -= arr[start]
            start += 1

        # If the sum is equal to X, increase the count by 1
        if sum_val == X:
            cnt += 1
            # Move the start pointer to the right
            sum_val -= arr[start]
            start += 1

        # Move the end pointer to the right
        end += 1

    return cnt

# Sample Input
N = 6
X = 5
arr = [1, 1, 1, 1, 1, 1]

print(solve(N, X, arr))

Output
2

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads