Count the number of subarrays | Practice | GeeksforGeeks

Given an array A[] of N integers and a range(L, R). The task is to find the number of subarrays having sum in the range L to R (inclusive).
Example 1:
Input:
N = 3, L = 3, R = 8
A[] = {1, 4, 6}
Output: 
3
Explanation: 
The subarrays are [1,4], [4] and [6]

Example 2:
Input:
N = 4, L = 4, R = 13
A[] = {2, 3, 5, 8}
Output: 
6
Explanation: 
The subarrays are [2,3], [2,3,5], 
[3,5],[5], [5,8] and [8]

Your Task: 
You don't need to read input or print anything. Complete the function countSubarray( ) which takes the integer N , the array A[], the integer L and the integer R as input parameters and returns the number of subarays. 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 106
1 ≤ A[] ≤ 109
1 ≤ L ≤ R ≤ 1015
+3
jayesh292 weeks ago
Java 0.85 sec -
long countSubarray(int N,int arr[],long L,long R) {
    long ans2 = count(N,arr,R);
    long ans1 = count(N,arr,L-1);
    return (ans2-ans1);
}
long count(int n,int arr[],long x){
    long ans=0, sum=0;
    for(int r=0,l=0;r<n;r++){
        sum+=arr[r];
        while(sum>x){
            sum-=arr[l++];
        }
        ans+=(r-l+1);
    }
    return ans;
}
0
masudkabir001 month ago
class Solution { public: long long int solve(vector<int>A,int N,long long int a){     long long j=0;     long long ans=0;     long long sum=0;     for(int i=0;i<N;i++){         sum+=A[i];         while(sum>a){             sum-=A[j];             j++;         }         ans+=i-j+1;              }     return ans; }   long long countSubarray(int N,vector<int> A,long long L,long long R) {       // code here       return solve(A,N,R)-solve(A,N,L-1);          }};
0
lindan1233 months ago
long long int help(int n, vector<int>&a, long long int num)
  {
      long long int st=0;
      long long int ans =0;
      long long int sum=0;
      for(long long int ed=0;ed<n;ed++)
      {
          sum+=a[ed];
          
          while(sum>num)
          {
              sum-=a[st];
              st++;
          }
          
          ans += ed-st+1;
      }
      return ans;
  }
    long long countSubarray(int N,vector<int> A,long long L,long long R) {
        return help(N,A,R)-help(N,A,L-1);
    }
Time Taken : 0.4
Cpp
0
tilmandressler5 months ago
Can someone help me? It works for all the test-cases I could come up but when I submit, it tells me it takes too long( although everything is instantanous on my machine)
I know its not O(N), but I'm doing the recommended arrays slider thing. Don't know how that's supposed to be O(N).
 
long long countSubarray(int N, vector<int> A, long long L, long long R) {

        int start_index = 0; //where the array slider starts
        int curr_index = 0; // where its atm
        long long partial_sum = 0; //the sum of array slider
        int result = 0; // how many arrays have been found
        while (curr_index != N)
        {
            partial_sum += A[curr_index];
            if (partial_sum > R) 
            {
                while (partial_sum > R && start_index != curr_index)
                {
                    partial_sum -= A[start_index];
                    start_index++;
                }
            }
            if (partial_sum > R)
            {
                curr_index++;
                start_index = curr_index;
                partial_sum = 0;
                continue;
            }
            if (partial_sum >= L) //lower boundary
            {

                long long lower_bound_sum = 0;
                int bound = curr_index;
                while (lower_bound_sum + A[bound] < L && bound != start_index)
                {
                    lower_bound_sum += A[bound];
                    bound--;
                }
                result += (bound - start_index + 1); 
            }
            curr_index++;
        }
        return result;

    }
+1
shagunagl75 months ago
class Solution {
 public:
   long long countSubarray(int n,vector<int> a,long long l,long long r) {
       // code here
       long long x=0,y=0;
       l=l-1;                       /*as reference-    leetcode.com/problems/binary-subarrays-with-sum/discuss/1174685/Sliding-Window-C%2B%2B-O(1)space*/
       x=helper(a,n,l);
       y=helper(a,n,r);
       return y-x;
   }
   long long helper(vector<int>&a,int n,long long t){
       long long i=0,j=0,sum=0,ans=0;
       while(j<n){
          sum+=a[j];
          while(sum>t){
              sum-=a[i];
              i++;
          }
          ans+=(j-i+1);
          j++;
       }
       return ans;
   }
};

+3
ritumodi55 months ago
We can solve this using sliding window and a key insight.
Getting the number of subarrays with sum in the range [L, R] using sliding window is difficult, but we can transform the problem into another easier one - Find number of subarrays with sum ≤ k.
How can we use that here?
Well, number of subarrays with sum in range [L, R] =  (number of subbarrays with the sum ≤ R) - (number of subarrays with sum ≤ L-1).
And that's it, the code then becomes pretty easy.
Here is my solution in Java:
 
class Solution { 
   long countSubarray(int N,int A[],long L,long R) {
       return count(A, R) - count(A, L-1);
   }
   
   // number of subarrays with sum <= limit
   private long count(int[] A, long limit){
       int i = 0, j = 0;
       long sum = 0, ans = 0;
       while(j < A.length){
           sum += A[j];
           while(sum > limit) sum -= A[i++];
           ans += j - i + 1;
           j++;
       }
       return ans;
   }
}
0
yashh2711
This comment was deleted.
+4
_beerus_sama_5 months ago
C++ easiest solution

#define ll long long
class Solution {
  public:
    
    /*
    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.
    */
    long long count_subarray_sum_less_than_k(int n,vector<int> &a,long long k)
    {
        ll res=0,l=0,r=0,csum=0;
        while(r<n)
        {
            csum += a[r];
            while(csum>k)
                csum -= a[l++];
                
            res += r-l+1;
            r++;
        }
        return res;
    }
  
    long long countSubarray(int n,vector<int> a,long long l,long long r) {
    // code here
    
        ll lessThanl_1 = count_subarray_sum_less_than_k(n,a,l-1);
        ll lessThanR = count_subarray_sum_less_than_k(n,a,r);
        
        return lessThanR - lessThanl_1;
    }
};
+6
tushargupta19995 months ago
Concise C++ solution
class Solution {
    long long countLessThan(vector<int> arr, long long lim) {
        long long ans = 0;
        for(long long i=0, j=0, cur=0; j<arr.size(); j++) {
            cur += arr[j];
            while(cur > lim) cur -= arr[i++];
            ans += j-i;
        }
        return ans;
    }
  public:
    long long countSubarray(int N,vector<int> A,long long L,long long R) {
        return countLessThan(A, R) - countLessThan(A,L-1);
    }
};
Ref: Number of subarrays having sum less than K
0
tyagianshika66
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.