Open In App

Number of subarrays having sum in a given range

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of integers and a range (L, R). Find the number of subarrays having sum in the range L to R.

Examples: 

Input: arr = [ -2, 4, 1, -2], lower = -4, upper = 1
Output: 5
Explaination:
The pairs that are present here are -
(1, 1) = [-2] , sum = -2
(1, 4) = [-2, 4, 1, -2] , sum = 1
(3, 3) = [1] , sum = 1
(3, 4) = [1, -2] , sum = -1
(4, 4) = [-2] , sum = -2

Input : arr[] = {2, 3, 5, 8}, L = 4, R = 13
Output : 6
The subarrays are {2, 3}, {2, 3, 5}, {3, 5},
{5}, {5, 8}, {8}.


Naive Approach:

The basic approach to solve this type of question is to try all possible case using brute force method and count all the pair whose sum lie in the range [lower, uppper].

Code –

C++
#include <iostream>
#include <vector>
using namespace std;

int getCount(vector<int> arr, int n, int lower, int upper) {
    int count = 0;
    for(int i=0; i<n; i++) {
        int sum = 0;
        for(int j=i; j<n; j++) {
            sum += arr[j];
            if(sum >= lower and sum <= upper) {
                count++;
            }
        }
    }
    return count;
}

int main() {
    int n = 4;
    vector<int> arr = {-2, 4, 1, -2};
    int lower = -4, upper = 1;
    int answer = getCount(arr, n, lower, upper);
    cout << answer << endl;
    return 0;
}


Time Complexity: O(n^2)

Space Complexity: O(1)

This Solution is Work for only Positive Numbers –

An efficient solution is to first find the number of subarrays having sum less than or equal to R. From this count, subtract the number of subarrays having sum less than or equal to L-1. To find the number of subarrays having sum less than or equal to the given value, the linear time method using the sliding window discussed in the following post is used: 

Number of subarrays having sum less than or equal to k.

Steps to solve this problem:

1. Declare a variable Rcnt and store the value of function countSub(arr,n,R)

2. Declare a variable lcnt and store the variable of function countSub(arr,n,L-1).

3. Return Rcnt-Lcnt.

    *In countSub function:

    1. Declare variables st=0,end=0,sum=0,and cnt=0.

    2. While end is smaller than n:

        *Update sum+=arr[end].

        *While St is smaller than equal to n and sum is greater than x:

             *Update sum-=arr[St] and increment St.

        *Update cnt+=(end-st+1) and increment end.

    3. Return cnt.

Below is the implementation of above approach:

C++
// CPP program to find number of subarrays having
// sum in the range L to R.
#include <bits/stdc++.h>
using namespace std;

// Function to find number of subarrays having
// sum less than or equal to x.
int countSub(int arr[], int n, int x)
{

    // Starting index of sliding window.
    int st = 0;

    // Ending index of sliding window.
    int end = 0;

    // Sum of elements currently present
    // in sliding window.
    int sum = 0;

    // To store required number of subarrays.
    int cnt = 0;

    // Increment ending index of sliding
    // window one step at a time.
    while (end < n) {

        // Update sum of sliding window on
        // adding a new element.
        sum += arr[end];

        // Increment starting index of sliding
        // window until sum is greater than x.
        while (st <= end && sum > x) {
            sum -= arr[st];
            st++;
        }

        // Update count of number of subarrays.
        cnt += (end - st + 1);
        end++;
    }

    return cnt;
}

// Function to find number of subarrays having
// sum in the range L to R.
int findSubSumLtoR(int arr[], int n, int L, int R)
{

    // Number of subarrays having sum less
    // than or equal to R.
    int Rcnt = countSub(arr, n, R);

    // Number of subarrays having sum less
    // than or equal to L-1.
    int Lcnt = countSub(arr, n, L - 1);

    return Rcnt - Lcnt;
}

// Driver code.
int main()
{
    int arr[] = { 1, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);

    int L = 3;
    int R = 8;

    cout << findSubSumLtoR(arr, n, L, R);
    return 0;
}
Java
// Java program to find number 
// of subarrays having sum in
// the range L to R.
import java.io.*;

class GFG
{
    
    // Function to find number
    // of subarrays having sum 
    // less than or equal to x.
    static int countSub(int arr[], 
                        int n, int x)
    {
    
        // Starting index of
        // sliding window.
        int st = 0;
    
        // Ending index of 
        // sliding window.
        int end = 0;
    
        // Sum of elements currently 
        // present in sliding window.
        int sum = 0;
    
        // To store required 
        // number of subarrays.
        int cnt = 0;
    
        // Increment ending index 
        // of sliding window one
        // step at a time.
        while (end < n) 
        {
    
            // Update sum of sliding 
            // window on adding a
            // new element.
            sum += arr[end];
    
            // Increment starting index 
            // of sliding window until
            // sum is greater than x.
            while (st <= end && sum > x) 
            {
                sum -= arr[st];
                st++;
            }
    
            // Update count of 
            // number of subarrays.
            cnt += (end - st + 1);
            end++;
        }
    
        return cnt;
    }
    
    // Function to find number 
    // of subarrays having sum 
    // in the range L to R.
    static int findSubSumLtoR(int arr[], int n,
                              int L, int R)
    {
    
        // Number of subarrays 
        // having sum less than 
        // or equal to R.
        int Rcnt = countSub(arr, n, R);
    
        // Number of subarrays 
        // having sum less than 
        // or equal to L-1.
        int Lcnt = countSub(arr, n, L - 1);
    
        return Rcnt - Lcnt;
    }
    
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = { 1, 4, 6 };
        int n = arr.length;
    
        int L = 3;
        int R = 8;
    
        System.out.println(findSubSumLtoR(arr, n, L, R));
    }
}

// This code is contributed
// by Mahadev99
Python 3
# Python 3 program to find
# number of subarrays having
# sum in the range L to R.

# Function to find number 
# of subarrays having sum
# less than or equal to x.
def countSub(arr, n, x):
    
    # Starting index of
    # sliding window.
    st = 0

    # Ending index of 
    # sliding window.
    end = 0

    # Sum of elements currently 
    # present in sliding window.
    sum = 0

    # To store required 
    # number of subarrays.
    cnt = 0

    # Increment ending index 
    # of sliding window one
    # step at a time.
    while end < n :
        
        # Update sum of sliding 
        # window on adding a
        # new element.
        sum += arr[end]

        # Increment starting index 
        # of sliding window until 
        # sum is greater than x.
        while (st <= end and sum > x) :
            sum -= arr[st]
            st += 1

        # Update count of
        # number of subarrays.
        cnt += (end - st + 1)
        end += 1

    return cnt

# Function to find number 
# of subarrays having sum 
# in the range L to R.
def findSubSumLtoR(arr, n, L, R):
    
    # Number of subarrays
    # having sum less
    # than or equal to R.
    Rcnt = countSub(arr, n, R)

    # Number of subarrays 
    # having sum less than
    # or equal to L-1.
    Lcnt = countSub(arr, n, L - 1)

    return Rcnt - Lcnt

# Driver code
arr = [ 1, 4, 6 ]
n = len(arr)
L = 3
R = 8
print(findSubSumLtoR(arr, n, L, R))

# This code is contributed 
# by ChitraNayal 
C#
// C# program to find number 
// of subarrays having sum in
// the range L to R.
using System;

class GFG
{
    
    // Function to find number
    // of subarrays having sum 
    // less than or equal to x.
    static int countSub(int[] arr, 
                        int n, int x)
    {
    
        // Starting index of
        // sliding window.
        int st = 0;
    
        // Ending index of 
        // sliding window.
        int end = 0;
    
        // Sum of elements currently 
        // present in sliding window.
        int sum = 0;
    
        // To store required 
        // number of subarrays.
        int cnt = 0;
    
        // Increment ending index 
        // of sliding window one
        // step at a time.
        while (end < n) 
        {
    
            // Update sum of sliding 
            // window on adding a
            // new element.
            sum += arr[end];
    
            // Increment starting index 
            // of sliding window until
            // sum is greater than x.
            while (st <= end && sum > x) 
            {
                sum -= arr[st];
                st++;
            }
    
            // Update count of 
            // number of subarrays.
            cnt += (end - st + 1);
            end++;
        }
    
        return cnt;
    }
    
    // Function to find number 
    // of subarrays having sum 
    // in the range L to R.
    static int findSubSumLtoR(int[] arr, int n,
                              int L, int R)
    {
    
        // Number of subarrays 
        // having sum less than 
        // or equal to R.
        int Rcnt = countSub(arr, n, R);
    
        // Number of subarrays 
        // having sum less than 
        // or equal to L-1.
        int Lcnt = countSub(arr, n, L - 1);
    
        return Rcnt - Lcnt;
    }
    
    // Driver code
    public static void Main ()
    {
        int[] arr = { 1, 4, 6 };
        int n = arr.Length;
    
        int L = 3;
        int R = 8;
    
        Console.Write(findSubSumLtoR(arr, n, L, R));
    }
}

// This code is contributed 
// by ChitraNayal
Javascript
<script>

// Javascript program to find number of subarrays having
// sum in the range L to R.

// Function to find number of subarrays having
// sum less than or equal to x.
function countSub(arr, n, x)
{

    // Starting index of sliding window.
    var st = 0;

    // Ending index of sliding window.
    var end = 0;

    // Sum of elements currently present
    // in sliding window.
    var sum = 0;

    // To store required number of subarrays.
    var cnt = 0;

    // Increment ending index of sliding
    // window one step at a time.
    while (end < n) {

        // Update sum of sliding window on
        // adding a new element.
        sum += arr[end];

        // Increment starting index of sliding
        // window until sum is greater than x.
        while (st <= end && sum > x) {
            sum -= arr[st];
            st++;
        }

        // Update count of number of subarrays.
        cnt += (end - st + 1);
        end++;
    }

    return cnt;
}

// Function to find number of subarrays having
// sum in the range L to R.
function findSubSumLtoR(arr, n, L, R)
{

    // Number of subarrays having sum less
    // than or equal to R.
    var Rcnt = countSub(arr, n, R);

    // Number of subarrays having sum less
    // than or equal to L-1.
    var Lcnt = countSub(arr, n, L - 1);

    return Rcnt - Lcnt;
}

// Driver code.
var arr = [ 1, 4, 6 ];
var n = arr.length;
var L = 3;
var R = 8;
document.write( findSubSumLtoR(arr, n, L, R));

</script>
PHP
<?php 
// PHP program to find number 
// of subarrays having sum 
// in the range L to R.

// Function to find number
// of subarrays having sum
// less than or equal to x.
function countSub(&$arr, $n, $x)
{
    // Starting index of
    // sliding window.
    $st = 0;

    // Ending index of
    // sliding window.
    $end = 0;

    // Sum of elements currently 
    // present in sliding window.
    $sum = 0;

    // To store required
    // number of subarrays.
    $cnt = 0;

    // Increment ending index 
    // of sliding window one
    // step at a time.
    while ($end < $n) 
    {
        // Update sum of sliding window 
        // on adding a new element.
        $sum += $arr[$end];

        // Increment starting index 
        // of sliding window until 
        // sum is greater than x.
        while ($st <= $end && $sum > $x) 
        {
            $sum -= $arr[$st];
            $st++;
        }

        // Update count of 
        // number of subarrays.
        $cnt += ($end - $st + 1);
        $end++;
    }

    return $cnt;
}

// Function to find number 
// of subarrays having sum
// in the range L to R.
function findSubSumLtoR(&$arr, $n, $L, $R)
{
    // Number of subarrays
    // having sum less
    // than or equal to R.
    $Rcnt = countSub($arr, $n, $R);

    // Number of subarrays 
    // having sum less
    // than or equal to L-1.
    $Lcnt = countSub($arr, $n, $L - 1);

    return $Rcnt - $Lcnt;
}

// Driver code.
$arr = array( 1, 4, 6 );
$n = sizeof($arr);
$L = 3;
$R = 8;
echo findSubSumLtoR($arr, $n, $L, $R);

// This code is contributed 
// by ChitraNayal
?>

Output
3

Complexity Analysis:

  • Time Complexity: O(n) 
  • Auxiliary Space: O(1)


Using Merge Sort ( Works for Both Positive and Negative Integers )

Prerequisite – Merge Sort

We will use Merge sort and prefix-sum to solve this problem. we will find the range from the small sorted arrays in the prefix array that lies in the range [lower, upper].

we use prefix array to track the sum and check if the pair lies in the range lower bound and upper bound then

lower <= prefix[j] – prefix[i-1] <= upper

or

lower + prefix[i-1] <= prefix[j] <= upper + prefix[i-1]

Following are the steps that need to follow –

1. Calculate mid of the array by using (start + end)/2;

2. Then Recursivly call the function in two seperate half (start, mid) and (mid+1, end).

3. After this Calls the two seperated array (start, mid) and (mid+1, end) are sorted in itself so we can calculate the range of the sum that lies in the prefix array.

4. We will iterate first half (let’s say i) and find the range in the second half(let’s say j) such that prefix[j] should lie in the given range [prefix[i-1 + lower, prefix[i-1]+ upper].

5. and count the number of pairs from the range.

6. when the iteration of i is finished. then we will merge the two half into a single array.

Code –

C++
#include <iostream>
#include <vector>
using namespace std;

// By Nitin Patel
void merge(long long start, long long end, vector<long long> &prefix) {
    long long n = end - start + 1;
    long long mid = (start + end)/2;
    vector<long long> temp(n, 0);
    long long i = start;
    long long j = mid+1;
    long long k = 0;
    while(i <= mid and j <= end) {
        if(prefix[i] <= prefix[j]) {
            temp[k++] = prefix[i++];
        }
        else {
            temp[k++] = prefix[j++];
        }
    }
    while(i <= mid) {
        temp[k++] = prefix[i++];
    }
    while(j <= end) {
        temp[k++] = prefix[j++]; 
    }
    for(int t=start; t<=end; t++) {
        prefix[t] = temp[t - start];
    }
}

long long mergeSort(long long start, long long end, vector<long long> &prefix, int lower, int upper) {
    if(start == end) {
        long long val = prefix[start];
        if(val >= (long long)lower and val <= (long long)upper) {
            return 1;
        }
        else {
            return 0;
        }
    }

    long long mid = (start + ((end - start) >> 1));
    long long ans = 0;
    ans += mergeSort(start, mid, prefix, lower, upper);
    ans += mergeSort(mid+1, end, prefix, lower, upper);
    long long i = start; long long j = mid+1; long long k = mid+1;
    while(i <= mid) {
        long long lowerbound = lower + prefix[i], upperbound = upper + prefix[i];
        while(j <= end and (prefix[j]) <= upperbound) {
            j++;
        }
        while(k <= end and (prefix[k]) < lowerbound) {
            k++;
        }
        ans += (j-k);
        i++;
    }
    merge(start, end, prefix);
    return ans;
}

int getCount(vector<int>& nums, int n, int lower, int upper) {

    vector<long long> prefix(n+1, 0);
    for(long long i=1; i<=n; i++) {
        prefix[i] = prefix[i-1] + nums[i-1];
    }
    return mergeSort(1, n, prefix, lower, upper);
}   

int main() {
    int n = 4;
    vector<int> arr = {-2, 4, 1, -2};
    int lower = -4, upper = 1;
    int answer = getCount(arr, n, lower, upper);
    cout << answer << endl;
    return 0;
}


Time Complexity: O(n log n)

Space Complexity: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads