Open In App

Count sub-arrays which have elements less than or equal to X

Last Updated : 25 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of n elements and an integer X. Count the number of sub-arrays of this array which have all elements less than or equal to X.

Examples: 

Input : arr[] = {1, 5, 7, 8, 2, 3, 9}  
            X = 6
Output : 6
Explanation : Sub-arrays are {1}, {5}, {2}, {3},
{1, 5}, {2, 3}

Input : arr[] =  {1, 10, 12, 4, 5, 3, 2, 7}   
            X = 9
Output : 16

Naive Approach : A simple approach uses two nested loops for generating all sub-arrays of the given an array and a loop to check whether all elements of a sub-array is less than or equal to X or not.
Time Complexity: O(n*n*n)

Efficient Approach: An efficient approach is to observe that we just want the count of those sub-arrays which have all elements less than or equal to X. We can create a binary array of 0s and 1s corresponding to the original array. If an element in the original is less than or equal to X, then the corresponding element in the binary array will be 1 otherwise 0. Now, our problem reduces to count the number of sub-arrays in this binary array which has all 1s. We can also see that for an array which has all 1s all of its sub-arrays will have only 1s and the total number of sub-arrays will be len*(len+1)/2. For example, {1, 1, 1, 1} will have 10 sub-arrays.

Below is the complete algorithm to solve the above problem: 

  • Create a corresponding binary array of the original array as described above.
  • Initialize a counter variable to 0 and start traversing the binary array keeping track of the lengths of sub-arrays which has all 1s
  • We can easily calculate the number of sub-arrays of an array which has all 1s by using the formula n*(n+1)/2, where n is the length of the array with all 1s.
  • Calculate the length of every sub-array which has all 1s and increment the count variable by length*(length+1)/2. We can do this in O(n) time complexity

Below is the implementation of above approach: 

C++




// C++ program to count all sub-arrays which
// has all elements less than or equal to X
#include <iostream>
using namespace std;
 
// function to count all sub-arrays which
// has all elements less than or equal to X
int countSubArrays(int arr[], int n, int x)
{
    // variable to keep track of length of
    // subarrays with all 1s
    int len = 0;
 
    // variable to keep track of all subarrays
    int count = 0;
 
    // binary array of same size
    int binaryArr[n];
 
    // creating binary array
    for (int i = 0; i < n; i++) {
        if (arr[i] <= x)
            binaryArr[i] = 1;
        else
            binaryArr[i] = 0;
    }
 
    // start traversing the binary array
    for (int i = 0; i < n; i++) {
 
        // once we find the first 1, keep checking
        // for number of consecutive 1s
        if (binaryArr[i] == 1) {
            int j;
 
            for (j = i + 1; j < n; j++)
                if (binaryArr[j] != 1)
                    break;
 
            // calculate length of the subarray
            // with all 1s
            len = j - i;
 
            // increment count
            count += (len) * (len + 1) / 2;
 
            // initialize i to j
            i = j;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 5, 7, 8, 2, 3, 9 };
    int x = 6;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countSubArrays(arr, n, x);
    return 0;
}


Java




// Java program to count all sub-arrays which
// has all elements less than or equal to X
import java.io.*;
 
class GFG {
     
    // function to count all sub-arrays which
    // has all elements less than or equal to X
    static int countSubArrays(int arr[], int n, int x)
    {
         
        // variable to keep track of length of
        // subarrays with all 1s
        int len = 0;
     
        // variable to keep track of all subarrays
        int count = 0;
     
        // binary array of same size
        int binaryArr[] = new int[n];
     
        // creating binary array
        for (int i = 0; i < n; i++) {
            if (arr[i] <= x)
                binaryArr[i] = 1;
            else
                binaryArr[i] = 0;
        }
     
        // start traversing the binary array
        for (int i = 0; i < n; i++) {
     
            // once we find the first 1, keep checking
            // for number of consecutive 1s
            if (binaryArr[i] == 1) {
                int j;
     
                for (j = i + 1; j < n; j++)
                    if (binaryArr[j] != 1)
                        break;
     
                // calculate length of the subarray
                // with all 1s
                len = j - i;
     
                // increment count
                count += (len) * (len + 1) / 2;
     
                // initialize i to j
                i = j;
            }
        }
     
        return count;
    }
     
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 5, 7, 8, 2, 3, 9 };
        int x = 6;
        int n = arr.length;
         
        System.out.println(countSubArrays(arr, n, x));
    }
}
 
// This code is contributed by Nikita Tiwari.


Python3




# python 3 program to count all sub-arrays which
# has all elements less than or equal to X
 
# function to count all sub-arrays which
# has all elements less than or equal to X
def countSubArrays(arr, n, x):
     
    # variable to keep track of length
    # of subarrays with all 1s
    len = 0
 
    # variable to keep track of
    # all subarrays
    count = 0
 
    # binary array of same size
    binaryArr = [0 for i in range(n)]
 
    # creating binary array
    for i in range(0, n, 1):
        if (arr[i] <= x):
            binaryArr[i] = 1
        else:
            binaryArr[i] = 0
 
    # start traversing the binary array
    for i in range(0, n, 1):
         
        # once we find the first 1,
        # keep checking for number
        # of consecutive 1s
        if (binaryArr[i] == 1):
            for j in range(i + 1, n, 1):
                if (binaryArr[j] != 1):
                    break
 
            # calculate length of the
            # subarray with all 1s
            len = j - i
 
            # increment count
            count += (len) * (int)((len + 1) / 2)
 
            # initialize i to j
            i = j
 
    return count
 
# Driver code
if __name__ == '__main__':
    arr = [1, 5, 7, 8, 2, 3, 9]
    x = 6
    n = len(arr)
    print(int(countSubArrays(arr, n, x)))
     
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to count all sub-arrays which
// has all elements less than or equal to X1
using System;
 
class GFG {
     
    // function to count all sub-arrays which
    // has all elements less than or equal
    // to X
    static int countSubArrays(int []arr,
                                int n, int x)
    {
         
        // variable to keep track of length
        // of subarrays with all 1s
        int len = 0;
     
        // variable to keep track of all
        // subarrays
        int count = 0;
     
        // binary array of same size
        int []binaryArr = new int[n];
     
        // creating binary array
        for (int i = 0; i < n; i++) {
            if (arr[i] <= x)
                binaryArr[i] = 1;
            else
                binaryArr[i] = 0;
        }
     
        // start traversing the binary array
        for (int i = 0; i < n; i++) {
     
            // once we find the first 1, keep
            // checking for number of
            // consecutive 1s
            if (binaryArr[i] == 1) {
                int j;
     
                for (j = i + 1; j< n; j++)
                    if (binaryArr[j] != 1)
                        break;
     
                // calculate length of the
                // subarray with all 1s
                len = j - i;
     
                // increment count
                count += (len) * (len + 1) / 2;
     
                // initialize i to j
                i = j;
            }
        }
     
        return count;
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = { 1, 5, 7, 8, 2, 3, 9 };
        int x = 6;
        int n = arr.Length;
         
        Console.WriteLine(
                    countSubArrays(arr, n, x));
    }
}
 
// This code is contributed by Sam007.


PHP




<?php
// PHP program to count all sub-arrays which
// has all elements less than or equal to X
 
// function to count all sub-arrays which
// has all elements less than or equal to X
function countSubArrays($arr, $n, $x)
{
     
    // variable to keep track of length of
    // subarrays with all 1s
    $len = 0;
 
    // variable to keep track of all subarrays
    $coun = 0;
 
    // binary array of same size
    $binaryArr = array($n);
 
    // creating binary array
    for ($i = 0; $i < $n; $i++)
    {
        if ($arr[$i] <= $x)
            $binaryArr[$i] = 1;
        else
            $binaryArr[$i] = 0;
    }
 
    // start traversing
    // the binary array
    for ($i = 0; $i < $n; $i++)
    {
 
        // once we find the first 1,
        // keep checking for number
        // of consecutive 1s
        if ($binaryArr[$i] == 1) {
             
 
            for ($j = $i + 1; $j < $n; $j++)
                if ($binaryArr[$j] != 1)
                    break;
 
            // calculate length of
            // the subarray with all 1s
            $len = $j - $i;
 
            // increment count
            $coun += ($len) * ($len + 1) / 2;
 
            // initialize i to j
            $i = $j;
        }
    }
 
    return $coun;
}
 
    // Driver code
    $arr = array( 1, 5, 7, 8, 2, 3, 9 );
    $x = 6;
    $n = count($arr);
    echo countSubArrays($arr, $n, $x);
 
// This code is contributed by Sam007
?>


Javascript




<script>
// javascript program to count all sub-arrays which
// has all elements less than or equal to X
 
    // function to count all sub-arrays which
    // has all elements less than or equal to X
    function countSubArrays(arr , n , x) {
 
        // variable to keep track of length of
        // subarrays with all 1s
        var len = 0;
 
        // variable to keep track of all subarrays
        var count = 0;
 
        // binary array of same size
        var binaryArr = Array(n).fill(0);
 
        // creating binary array
        for (i = 0; i < n; i++) {
            if (arr[i] <= x)
                binaryArr[i] = 1;
            else
                binaryArr[i] = 0;
        }
 
        // start traversing the binary array
        for (i = 0; i < n; i++) {
 
            // once we find the first 1, keep checking
            // for number of consecutive 1s
            if (binaryArr[i] == 1) {
                var j;
 
                for (j = i + 1; j < n; j++)
                    if (binaryArr[j] != 1)
                        break;
 
                // calculate length of the subarray
                // with all 1s
                len = j - i;
 
                // increment count
                count += (len) * (len + 1) / 2;
 
                // initialize i to j
                i = j;
            }
        }
 
        return count;
    }
 
    // Driver code
        var arr = [ 1, 5, 7, 8, 2, 3, 9 ];
        var x = 6;
        var n = arr.length;
 
        document.write(countSubArrays(arr, n, x));
 
// This code is contributed by Rajput-Ji
</script>


Output: 

6

Time Complexity: O(n), where n is the number of elements in the array. 
Auxiliary Space: O(n).

Another Method: We can improve the above solution without using extra space keeping the time complexity O(n). Instead of marking elements as 0 and 1 we can keep track of start and end of each such region and update the count whenever the region ends. 

Implementation:

C++




// C++ program to count all sub-arrays which
// has all elements less than or equal to X
 
#include<bits/stdc++.h>
using namespace std;
 
int countSubArrays(int arr[], int x, int n )
    {
        int count = 0;
        int start = -1, end = -1;
     
        for(int i = 0; i < n; i++)
        {
            if(arr[i] < x)
            {
                if(start == -1)
                {
                     
                    //create a new subArray
                    start = i;
                    end = i;
                }
                else
                {
                     
                    // append to existing subarray
                    end=i;
                }
            }
            else
            {
                if(start != -1 && end != -1)
                {
                     
                    // given start and end calculate
                    // all subarrays within this range
                    int length = end - start + 1;
                    count = count + ((length * (length + 1)) / 2);
                }
                 
                start = -1;
                end = -1;
            }
 
        }
         
        if(start != -1 && end != -1)
        {
             
            // given start and end calculate all
            // subarrays within this range
            int length = end - start + 1;
            count = count + ((length * (length + 1)) / 2);
        }
         
        return count;
    }
     
    // Driver code
int main()
    {
        int arr[] = { 1, 5, 7, 8, 2, 3, 9 };
        int x = 6;
        int n = sizeof(arr) / sizeof(arr[0]);
        cout<< countSubArrays(arr, x, n);
         
//This code is contributed by  29AjayKumar
 
    }


Java




// Java program to count all sub-arrays which
// has all elements less than or equal to X
 
public class GFG {
 
    public static int countSubArrays(int arr[], int x)
    {
        int count = 0;
        int start = -1, end = -1;
         
        for(int i = 0; i < arr.length; i++)
        {
            if(arr[i] < x)
            {
                if(start == -1)
                {
                     
                    //create a new subArray
                    start = i;
                    end = i;
                }
                else
                {
                     
                    // append to existing subarray
                    end=i;
                }
            }
            else
            {
                if(start != -1 && end != -1)
                {
                     
                    // given start and end calculate
                    // all subarrays within this range
                    int length = end - start + 1;
                    count = count + ((length * (length + 1)) / 2);
                }
                 
                start = -1;
                end = -1;
            }
 
        }
         
        if(start != -1 && end != -1)
        {
             
            // given start and end calculate all
            // subarrays within this range
            int length = end - start + 1;
            count = count + ((length * (length + 1)) / 2);
        }
         
        return count;
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 5, 7, 8, 2, 3, 9 };
        int x = 6;
        System.out.println(countSubArrays(arr, x));
 
    }
}


Python3




# Python3 program to count all sub-arrays which
# has all elements less than or equal to X
 
def countSubArrays(arr, x, n ):
    count = 0;
    start = -1; end = -1;
 
    for i in range(n):
        if(arr[i] < x):
            if(start == -1):
 
                # create a new subArray
                start = i;
                end = i;
            else:
                 
                # append to existing subarray
                end = i;
        else:
            if(start != -1 and end != -1):
 
                # given start and end calculate
                # all subarrays within this range
                length = end - start + 1;
                count = count + ((length *
                                 (length + 1)) / 2);
            start = -1;
            end = -1;
 
    if(start != -1 and end != -1):
 
        # given start and end calculate all
        # subarrays within this range
        length = end - start + 1;
        count = count + ((length *
                         (length + 1)) / 2);
 
    return count;
 
# Driver code
arr = [ 1, 5, 7, 8, 2, 3, 9 ];
x = 6;
n = len(arr);
print(countSubArrays(arr, x, n));
 
# This code is contributed
# by PrinciRaj1992


C#




// C# program to count all sub-arrays which
// has all elements less than or equal to X
using System;
 
class GFG
{
 
    public static int countSubArrays(int []arr, int x)
    {
        int count = 0;
        int start = -1, end = -1;
         
        for(int i = 0; i < arr.Length; i++)
        {
            if(arr[i] < x)
            {
                if(start == -1)
                {
                     
                    //create a new subArray
                    start = i;
                    end = i;
                }
                else
                {
                     
                    // append to existing subarray
                    end=i;
                }
            }
            else
            {
                if(start != -1 && end != -1)
                {
                     
                    // given start and end calculate
                    // all subarrays within this range
                    int length = end - start + 1;
                    count = count + ((length * (length + 1)) / 2);
                }
                 
                start = -1;
                end = -1;
            }
 
        }
         
        if(start != -1 && end != -1)
        {
             
            // given start and end calculate all
            // subarrays within this range
            int length = end - start + 1;
            count = count + ((length * (length + 1)) / 2);
        }
         
        return count;
    }
     
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = { 1, 5, 7, 8, 2, 3, 9 };
        int x = 6;
        Console.WriteLine(countSubArrays(arr, x));
    }
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
    // Javascript program to count all sub-arrays which
    // has all elements less than or equal to X
     
    function countSubArrays(arr, x)
    {
        let count = 0;
        let start = -1, end = -1;
          
        for(let i = 0; i < arr.length; i++)
        {
            if(arr[i] < x)
            {
                if(start == -1)
                {
                      
                    //create a new subArray
                    start = i;
                    end = i;
                }
                else
                {
                      
                    // append to existing subarray
                    end=i;
                }
            }
            else
            {
                if(start != -1 && end != -1)
                {
                      
                    // given start and end calculate
                    // all subarrays within this range
                    let length = end - start + 1;
                    count = count + parseInt((length * (length + 1)) / 2, 10);
                }
                  
                start = -1;
                end = -1;
            }
  
        }
          
        if(start != -1 && end != -1)
        {
              
            // given start and end calculate all
            // subarrays within this range
            let length = end - start + 1;
            count = count + parseInt((length * (length + 1)) / 2, 10);
        }
          
        return count;
    }
     
    let arr = [ 1, 5, 7, 8, 2, 3, 9 ];
    let x = 6;
    document.write(countSubArrays(arr, x));
     
</script>


Output: 

6

Time Complexity: O(n), where n is the number of elements in the array. 
Auxiliary Space: O(1).



Similar Reads

Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
16 min read
Number of non-decreasing sub-arrays of length less than or equal to K
Given an array arr[] of N elements and an integer K, the task is to find the number of non-decreasing sub-arrays of length less than or equal to K.Examples: Input: arr[] = {1, 2, 3}, K = 2 Output: 5 {1}, {2}, {3}, {1, 2} and {2, 3} are the valid subarrays.Input: arr[] = {3, 2, 1}, K = 1 Output: 3 Naive approach: A simple approach is to generate all
6 min read
Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which elements greater than a given number K are more than elements not greater than K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray of length 4 or
10 min read
Minimum flips to make mean of all k size sub-arrays less than 1
Given an array A of size N, having each element either 0 or 1 and an integer K. Find the minimum number of elements that need to be flipped, such that no sub-array of size greater than or equal to K has an arithmetic mean of 1. Examples: Input: N = 5, A = {1, 1, 1, 1, 1}, K = 5Output: 1Explanation: Initially, mean of only sub-array of size 5 is (1+
11 min read
Find the number of positive integers less than or equal to N that have an odd number of digits
Given an integer N where 1 ? N ? 105, the task is to find the number of positive integers less than or equal to N that have an odd number of digits without leading zeros.Examples: Input: N = 11 Output: 9 1, 2, 3, ..., 8 and 9 are the numbers ? 11 with odd number of digits. Input: N = 893 Output: 803 Naive approach: Traverse from 1 to N and for each
4 min read
Count number of integers less than or equal to N which has exactly 9 divisors
Given a number N(1&lt;=N&lt;=109), the task is to find the total number of integers less than equal to n which have exactly 9 divisors. Examples: Input: N = 100 Output: 2 The two numbers which have exactly 9 divisors are 36 and 100. Input: N = 1000 Output: 8 The numbers are 36 100 196 225 256 441 484 676 A naive approach is to iterate for all numbe
13 min read
Number of sub-sequence such that it has one consecutive element with difference less than or equal to 1
Given an array arr[] of N elements. The task is to find the number of sub-sequences which have at least two consecutive elements such that absolute difference between them is ? 1. Examples: Input: arr[] = {1, 6, 2, 1} Output: 6 {1, 2}, {1, 2, 1}, {2, 1}, {6, 2, 1}, {1, 1} and {1, 6, 2, 1} are the sub-sequences that have at least one consecutive pai
7 min read
Longest sub-string having frequency of each character less than equal to k
Given a string str of length n. The problem is to find the length of the longest sub-string in str having frequency of each character less than equal to the given value k. Examples : Input : str = "babcaag", k = 1 Output : 3 abc and bca are the two longest sub-strings having frequency of each character in them less than equal to '1'. Input : str =
10 min read
Count of players who need training and have strictly less power and endurance than any other player
Given 2D array players with three components [power, endurance, id]. A player needs training if it has strictly less power and endurance than any other player. The task is to find the number of players who need training with their ids. Examples: Input: {{5, 4, 1}, {6, 3, 2}, {3, 5, 3}}Output: 0Explanation: There is no player which has strictly grea
8 min read
Article Tags :
Practice Tags :