Open In App

Count subarrays with all elements greater than K

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of n integers and an integer k, the task is to find the number of subarrays such that all elements in each subarray are greater than k.

Examples: 

Input: arr[] = {3, 4, 5, 6, 7, 2, 10, 11}, k= 5 
Output: 6 
The possible subarrays are {6}, {7}, {6, 7}, {10}, {11} and {10, 11}.

Input: arr[] = {8, 25, 10, 19, 19, 18, 20, 11, 18}, k = 13 
Output: 12  

[Naive Approach] Using two nested loops

The idea is to use two nested loops where the outer loop selects the starting point of potential subarrays, and for each starting point, the inner loop extends the subarray as long as all elements encountered are greater than k. When we find a valid subarray (all elements > k), we increment our count. The inner loop breaks as soon as we find an element less than or equal to k since any further extension of that subarray would be invalid.

C++
// C++ program to print the number of subarrays such
// that all elements are greater than K
#include <iostream>
#include <vector>
using namespace std;

// Function to count number of subarrays
int countSubarrays(vector<int> &arr, int k) {

    int n = arr.size();
    int count = 0;

    // First loop to select starting point
    for (int i = 0; i < n; i++) {

        // Second loop to extend the subarray
        for (int j = i; j < n; j++) {

            // If we find an element <= x, break
            if (arr[j] <= k)
                break;

            // If all elements so far are > x,
            // we found a valid subarray
            count++;
        }
    }
    return count;
}

int main() {
    vector<int> arr = {3, 4, 5, 6, 7, 2, 10, 11};
    int k = 5;
    cout << countSubarrays(arr, k);
    return 0;
}
Java
// Java program to print the number of subarrays such
// that all elements are greater than K
import java.util.*;

class GfG {

    // Function to count number of subarrays
    static int countSubarrays(int[] arr, int k) {

        int n = arr.length;
        int count = 0;

        // First loop to select starting point
        for (int i = 0; i < n; i++) {

            // Second loop to extend the subarray
            for (int j = i; j < n; j++) {

                // If we find an element <= x, break
                if (arr[j] <= k)
                    break;

                // If all elements so far are > x,
                // we found a valid subarray
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = { 3, 4, 5, 6, 7, 2, 10, 11 };
        int k = 5;
        System.out.println(countSubarrays(arr, k));
    }
}
Python
# Python program to print the number of subarrays such
# that all elements are greater than K

# Function to count number of subarrays
def countSubarrays(arr, k):
    count = 0
    n = len(arr)

    # First loop to select starting point
    for i in range(n):

        # Second loop to extend the subarray
        for j in range(i, n):

            # If we find an element <= k, break
            if arr[j] <= k:
                break

            # If all elements so far are > k,
            # we found a valid subarray
            count += 1

    return count


if __name__ == "__main__":
    arr = [3, 4, 5, 6, 7, 2, 10, 11]
    k = 5
    print(countSubarrays(arr, k))
C#
// C# program to print the number of subarrays such
// that all elements are greater than K
using System;

class GfG {

    // Function to count number of subarrays
    static int countSubarrays(int[] arr, int k) {
        int count = 0;
        int n = arr.Length;

        // First loop to select starting point
        for (int i = 0; i < n; i++) {

            // Second loop to extend the subarray
            for (int j = i; j < n; j++) {

                // If we find an element <= k, break
                if (arr[j] <= k)
                    break;

                // If all elements so far are > k,
                // we found a valid subarray
                count++;
            }
        }
        return count;
    }

    static void Main(string[] args) {
        int[] arr = { 3, 4, 5, 6, 7, 2, 10, 11 };
        int k = 5;
        Console.WriteLine(countSubarrays(arr, k));
    }
}
JavaScript
// JavaScript program to print the number of subarrays such
// that all elements are greater than K

// Function to count number of subarrays
function countSubarrays(arr, k) {
    let count = 0;
    let n = arr.length; // Get the length of the array

    // First loop to select starting point
    for (let i = 0; i < n; i++) {

        // Second loop to extend the subarray
        for (let j = i; j < n; j++) {

            // If we find an element <= k, break
            if (arr[j] <= k)
                break;

            // If all elements so far are > k,
            // we found a valid subarray
            count++;
        }
    }
    return count;
}

const arr = [ 3, 4, 5, 6, 7, 2, 10, 11 ];
const k = 5;
console.log(countSubarrays(arr, k));

Output
6

Time Complexity: O(n^2), as two loops are used.
Auxiliary Space: O(1)

[Expected Approach] Using Sliding Window

The idea is to use a sliding window approach where we maintain a window that contains elements greater than k. When we encounter an element greater than k, we can form subarrays using all previous valid elements in our window. If we find an element less than or equal to k, we reset our window by moving the start pointer to the next position, as no subarray containing this element can be valid.

Step by step implementation:

  • Maintain two pointers start and end where start marks the beginning of current valid window and end explores new elements.
  • When we find an element > k at index end, we can form (end - start + 1) new subarrays all ending at current element.
  • If we find an element ≤ k, we reset our window by moving start to end + 1 as no valid subarray can include this element.
C++
// C++ program to print the number of subarrays such
// that all elements are greater than K
#include <bits/stdc++.h>
using namespace std;

// Function to count number of subarrays
int countSubarrays(vector<int> &arr, int k) {
    int count = 0;
    int start = 0;
    int n = arr.size();

    for (int end = 0; end < n; end++) {

        // If current element <= k,
        // reset the window & continue.
        if (arr[end] <= k) {
            start = end + 1;
            continue;
        }

        // Count all possible subarrays
        // ending at 'end'
        count += (end - start + 1);
    }

    return count;
}

int main() {
    vector<int> arr = {3, 4, 5, 6, 7, 2, 10, 11};
    int k = 5;
    cout << countSubarrays(arr, k);
    return 0;
}
Java
// Java program to print the number of subarrays such
// that all elements are greater than K
import java.util.*;

class GfG {

    // Function to count number of subarrays
    static int countSubarrays(int[] arr, int k) {
        int count = 0;
        int start = 0;
        int n = arr.length;

        for (int end = 0; end < n; end++) {

            // If current element <= k,
            // reset the window & continue.
            if (arr[end] <= k) {
                start = end + 1;
                continue;
            }

            // Count all possible subarrays
            // ending at 'end'
            count += (end - start + 1);
        }

        return count;
    }

    public static void main(String[] args) {
        int[] arr = { 3, 4, 5, 6, 7, 2, 10, 11 };
        int k = 5;
        System.out.println(countSubarrays(arr, k));
    }
}
Python
# Python program to print the number of subarrays such
# that all elements are greater than K

# Function to count number of subarrays
def countSubarrays(arr, k):
    count = 0
    start = 0
    n = len(arr)  # Get the length of the array

    for end in range(n):

        # If current element <= k,
        # reset the window & continue.
        if arr[end] <= k:
            start = end + 1
            continue

        # Count all possible subarrays
        # ending at 'end'
        count += (end - start + 1)

    return count


if __name__ == "__main__":
    arr = [3, 4, 5, 6, 7, 2, 10, 11]
    k = 5
    print(countSubarrays(arr, k))
C#
// C# program to print the number of subarrays such
// that all elements are greater than K
using System;

class GfG {

    // Function to count number of subarrays
    static int countSubarrays(int[] arr, int k) {
        int count = 0;
        int start = 0;
        int n = arr.Length; 

        for (int end = 0; end < n; end++) {

            // If current element <= k,
            // reset the window & continue.
            if (arr[end] <= k) {
                start = end + 1;
                continue;
            }

            // Count all possible subarrays
            // ending at 'end'
            count += (end - start + 1);
        }

        return count;
    }

    static void Main(string[] args) {
        int[] arr = { 3, 4, 5, 6, 7, 2, 10, 11 };
        int k = 5;
        Console.WriteLine(countSubarrays(arr, k));
    }
}
JavaScript
// JavaScript program to print the number of subarrays such
// that all elements are greater than K

// Function to count number of subarrays
function countSubarrays(arr, k) {
    let count = 0;
    let start = 0;
    let n = arr.length;

    for (let end = 0; end < n; end++) {

        // If current element <= k,
        // reset the window & continue.
        if (arr[end] <= k) {
            start = end + 1;
            continue;
        }

        // Count all possible subarrays
        // ending at 'end'
        count += (end - start + 1);
    }

    return count;
}

const arr = [ 3, 4, 5, 6, 7, 2, 10, 11 ];
const k = 5;
console.log(countSubarrays(arr, k));

Output
6

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

Related Topic: Subarrays, Subsequences, and Subsets in Array


Next Article
Practice Tags :

Similar Reads