Count of Subarrays whose first element is the minimum
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++
#include <bits/stdc++.h>
using namespace std;
int countSubarrays(vector< int >& arr)
{
int n = arr.size();
int cnt = n;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
int mini_ele = *min_element(begin(arr) + i + 1,
begin(arr) + j + 1);
if (mini_ele >= arr[i])
cnt++;
}
}
return cnt;
}
int main()
{
vector< int > arr = { 1, 3, 5, 2 };
cout << countSubarrays(arr) << "\n" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static int min_element( int arr[], int left, int right)
{
int x = Integer.MAX_VALUE;
for ( int i=left;i<right;i++)
{
x=Math.min(x,arr[i]);
}
return x;
}
public static int countSubarrays( int arr[])
{
int n = arr.length;
int cnt = n;
for ( int i= 0 ;i<n;i++)
{
for ( int j=i+ 1 ;j<n;j++)
{
int mini_ele = min_element(arr,i+ 1 ,j+ 1 );
if (mini_ele >= arr[i])
cnt++;
}
}
return cnt;
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 5 , 2 };
System.out.println(countSubarrays(arr) );
}
}
|
Python3
import sys
def min_element(arr, left, right):
x = sys.maxsize
for i in range (left, right):
x = min (arr[i], x)
return x
def countSubarrays(arr):
n = len (arr)
cnt = n
for i in range (n):
for j in range (i + 1 ,n):
mini_ele = min_element(arr ,i + 1 , j + 1 )
if (mini_ele > = arr[i]):
cnt + = 1
return cnt
arr = [ 1 , 3 , 5 , 2 ]
print (countSubarrays(arr))
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static int min_element( int []arr, int left, int right)
{
int x = int .MaxValue;
for ( int i=left;i<right;i++)
{
x=Math.Min(x,arr[i]);
}
return x;
}
public static int countSubarrays( int []arr)
{
int n = arr.Length;
int cnt = n;
for ( int i=0;i<n;i++)
{
for ( int j=i+1;j<n;j++)
{
int mini_ele = min_element(arr,i+1,j+1);
if (mini_ele >= arr[i])
cnt++;
}
}
return cnt;
}
public static void Main(String[] args)
{
int []arr = {1, 3, 5, 2};
Console.WriteLine(countSubarrays(arr) );
}
}
|
Javascript
<script>
function min_element(arr,left,right){
let x = Number.MAX_VALUE
for (let i=left;i<right;i++){
x = Math.min(arr[i],x)
}
return x
}
function countSubarrays(arr)
{
let n = arr.length
let cnt = n
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let mini_ele = min_element(arr ,i + 1, j + 1);
if (mini_ele >= arr[i])
cnt++;
}
}
return cnt;
}
let arr = [ 1, 3, 5, 2 ];
document.write(countSubarrays(arr), "</br>" );
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
int countSubarrays(vector< int >& arr)
{
stack< int > s;
int ans = 0;
int n = arr.size();
for ( int i = n - 1; i >= 0; i--) {
while (!s.empty() and arr[s.top()] >= arr[i])
s.pop();
int last = (s.empty() ? n : s.top());
ans += (last - i);
s.push(i);
}
return ans;
}
int main()
{
vector< int > arr = { 1, 3, 5, 2 };
cout << countSubarrays(arr) << "\n" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int countSubarrays( int arr[])
{
Stack<Integer> s = new Stack<Integer>();
int ans = 0 ;
int n = arr.length;
for ( int i = n - 1 ; i >= 0 ; i--) {
while (s.empty() == false
&& arr[s.peek()] >= arr[i])
s.pop();
int last = ((s.empty() == true ) ? n : s.peek());
ans += (last - i);
s.push(i);
}
return ans;
}
public static void main(String[] args)
{
int arr[] = new int [] { 1 , 3 , 5 , 2 };
System.out.println(countSubarrays(arr));
}
}
|
Python3
def countSubarrays(arr):
s = []
ans = 0
n = len (arr)
for i in range (n - 1 , - 1 , - 1 ):
while ( len (s) ! = 0 and arr[s[ - 1 ]] > = arr[i]):
s.pop()
if ( len (s) = = 0 ):
last = n
else :
last = s[ - 1 ]
ans + = (last - i)
s.append(i)
return ans
if __name__ = = "__main__" :
arr = [ 1 , 3 , 5 , 2 ]
print (countSubarrays(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static int countSubarrays(List< int > arr)
{
Stack< int > s = new Stack< int >();
int ans = 0;
int n = arr.Count;
for ( int i = n - 1 ; i >= 0 ; i--) {
while (s.Count > 0 && arr[s.Peek()] >= arr[i]){
s.Pop();
}
int last = (s.Count == 0 ? n : s.Peek());
ans += (last - i);
s.Push(i);
}
return ans;
}
public static void Main( string [] args){
List< int > arr = new List< int >{
1, 3, 5, 2
};
Console.Write(countSubarrays(arr));
}
}
|
Javascript
<script>
const countSubarrays = (arr) => {
let s = [];
let ans = 0;
let n = arr.length;
for (let i = n - 1; i >= 0; i--)
{
while (s.length != 0 && arr[s[s.length - 1]] >= arr[i])
s.pop();
let last = (s.length == 0 ? n : s[s.length - 1]);
ans += (last - i);
s.push(i);
}
return ans;
}
let arr = [1, 3, 5, 2];
document.write(countSubarrays(arr));
</script>
|
Time Complexity:
Auxiliary Space:
Last Updated :
01 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...