The Wayback Machine - https://web.archive.org/web/20220302172242/https://www.geeksforgeeks.org/count-of-subarrays-whose-first-element-is-the-minimum/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of Subarrays whose first element is the minimum

  • Difficulty Level : Medium
  • Last Updated : 02 Mar, 2022

Given an array arr[] of size N, the task is to find the number of subarrays whose first element is not greater than other elements of the subarray.

Examples:

Input: arr = {1, 2, 1}
Output: 5
Explanation: All subarray are: {1}, {1, 2}, {1, 2, 1}, {2}, {2, 1}, {1}
From above subarray the following meets the condition: {1}, {1, 2}, {1, 2, 1}, {2}, {1}

Input: arr[] = {1, 3, 5, 2}
Output: 8
Explanation: We have the following subarrays which meet the condition:
{1}, {1, 3}, {1, 3, 5}, {1, 3, 5, 2}, {3}, {3, 5}, {5}, {2}

 

Naive Approach: The naive approach is to run a nested loop and find all the subarrays with first element not bigger than the other elements in the subarray.

Below is the implementation of the above approach :

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find all subarrays with first
// element not bigger than other elements
int countSubarrays(vector<int>& arr)
{
    int n = arr.size();
 
    // Cnt is intialised to n because
    // atleast n subarrays will be there
    // which is single element itself
    int cnt = n;
 
    // Two loops to find the
    // ending of each subarrays
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Minimum element from
            // [start+1, end] of each subarray
            int mini_ele = *min_element(begin(arr) + i + 1,
                                        begin(arr) + j + 1);
 
            // Checking if minimum of
            // elements from [start+1, end] is
            // not smaller than start element
            // updating the count of subarrays
            if (mini_ele >= arr[i])
                cnt++;
        }
    }
    return cnt;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 3, 5, 2 };
 
    // Function call
    cout << countSubarrays(arr) << "\n";
    return 0;
}

 
 

Output
8

 

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

 

Efficient Approach:  The efficient approach is based on the concept of finding the next smaller element on the right of an element. To implement this concept stack is used. Follow the steps mentioned below:

 

  • We use a monotonic stack to get the index of the next smaller of each element on the right because we want the subarray with first element as the minimum element.
  • The total subarray’s in the range [i, j] having i as the starting index is (j – i).
  • Compute the next smaller index for every index i, add (j-i) for each of them and keep updating the total count of valid subarrays.

 

Below is the implementation of the above approach.

 

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find all subarrays with first
// element not bigger than other elements
int countSubarrays(vector<int>& arr)
{
    // Taking stack for find next smaller
    // element to the right
    stack<int> s;
    int ans = 0;
    int n = arr.size();
 
    // Looping from right side because we next
    // smallest to the right
    for (int i = n - 1; i >= 0; i--) {
        while (!s.empty() and arr[s.top()] >= arr[i])
            s.pop();
        // The index of next smaller element
        // starting from i'th index
        int last = (s.empty() ? n : s.top());
 
        // Adding the number of subarray which
        // can be formed in the range [i, last]
        ans += (last - i);
        s.push(i);
    }
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 3, 5, 2 };
 
    // Function call
    cout << countSubarrays(arr) << "\n";
    return 0;
}

Javascript




<script>
    // JavaScript code to implement the approach
 
    // Function to find all subarrays with first
    // element not bigger than other elements
    const countSubarrays = (arr) => {
     
        // Taking stack for find next smaller
        // element to the right
        let s = [];
        let ans = 0;
        let n = arr.length;
 
        // Looping from right side because we next
        // smallest to the right
        for (let i = n - 1; i >= 0; i--)
        {
            while (s.length != 0 && arr[s[s.length - 1]] >= arr[i])
                s.pop();
                 
            // The index of next smaller element
            // starting from i'th index
            let last = (s.length == 0 ? n : s[s.length - 1]);
 
            // Adding the number of subarray which
            // can be formed in the range [i, last]
            ans += (last - i);
            s.push(i);
        }
        return ans;
    }
 
    // Driver Code
 
    let arr = [1, 3, 5, 2];
 
    // Function call
    document.write(countSubarrays(arr));
 
    // This code is contributed by rakeshsahni
 
</script>

 
 

Output
8

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!