Count of Subarrays whose first element is the minimum
Last Updated :
01 Jul, 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 initialised 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;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to find the minimum element in a given range
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;
}
// Function to find all subarrays with first
// element not bigger than other elements
public static int countSubarrays(int arr[])
{
int n = arr.length;
// Cnt is initialised 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(arr,i+1,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
public static void main(String[] args)
{
int arr[] = {1, 3, 5, 2};
// Function call
System.out.println(countSubarrays(arr) );
}
}
// This code is contributed by Aditya Patil
Python3
# Python3 code to implement the approach
# Function to find all subarrays with first
# element not bigger than other elements
# Function to find the minimum element in a given range
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 is initialised to n because
# atleast n subarrays will be there
# which is single element itself
cnt = n
# Two loops to find the
# ending of each subarrays
for i in range(n):
for j in range(i+1,n):
# Minimum element from
# [start+1, end] of each subarray
mini_ele = min_element(arr ,i + 1, 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 += 1
return cnt
# Driver Code
arr = [ 1, 3, 5, 2 ]
# Function call
print(countSubarrays(arr))
# This code is contributed by shinjanpatra
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
public class GFG
{
// Function to find the minimum element in a given range
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;
}
// Function to find all subarrays with first
// element not bigger than other elements
public static int countSubarrays(int []arr)
{
int n = arr.Length;
// Cnt is initialised 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(arr,i+1,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
public static void Main(String[] args)
{
int []arr = {1, 3, 5, 2};
// Function call
Console.WriteLine(countSubarrays(arr) );
}
}
// This code contributed by shikhasingrajput
JavaScript
<script>
// JavaScript code to implement the approach
// Function to find all subarrays with first
// element not bigger than other elements
// Function to find the minimum element in a given range
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
// Cnt is initialised to n because
// atleast n subarrays will be there
// which is single element itself
let cnt = n
// Two loops to find the
// ending of each subarrays
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Minimum element from
// [start+1, end] of each subarray
let mini_ele = min_element(arr ,i + 1, 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
let arr = [ 1, 3, 5, 2 ];
// Function call
document.write(countSubarrays(arr),"</br>");
// This code is contributed by shinjanpatra
</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++
// 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;
}
Java
// JAVA code to implement the approach
import java.util.*;
class GFG {
// Function to find all subarrays with first
// element not bigger than other elements
public static int countSubarrays(int arr[])
{
// Taking stack for find next smaller
// element to the right
Stack<Integer> s = new Stack<Integer>();
int ans = 0;
int n = arr.length;
// Looping from right side because we next
// smallest to the right
for (int i = n - 1; i >= 0; i--) {
while (s.empty() == false
&& arr[s.peek()] >= arr[i])
s.pop();
// The index of next smaller element
// starting from i'th index
int last = ((s.empty() == true) ? n : s.peek());
// Adding the number of subarray which
// can be formed in the range [i, last]
ans += (last - i);
s.push(i);
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = new int[] { 1, 3, 5, 2 };
// Function call
System.out.println(countSubarrays(arr));
}
}
// This code is contributed by Taranpreet
Python3
# Python 3 code to implement the approach
# Function to find all subarrays with first
# element not bigger than other elements
def countSubarrays(arr):
# Taking stack for find next smaller
# element to the right
s = []
ans = 0
n = len(arr)
# Looping from right side because we next
# smallest to the right
for i in range(n - 1, -1, -1):
while (len(s) != 0 and arr[s[-1]] >= arr[i]):
s.pop()
# The index of next smaller element
# starting from i'th index
if (len(s) == 0):
last = n
else:
last = s[-1]
# Adding the number of subarray which
# can be formed in the range [i, last]
ans += (last - i)
s.append(i)
return ans
# Driver Code
if __name__ == "__main__":
arr = [1, 3, 5, 2]
# Function call
print(countSubarrays(arr))
# This code is contributed by ukasp.
C#
// C# program to implement above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find all subarrays with first
// element not bigger than other elements
public static int countSubarrays(List<int> arr)
{
// Taking stack for find next smaller
// element to the right
Stack<int> s = new Stack<int>();
int ans = 0;
int n = arr.Count;
// Looping from right side because we next
// smallest to the right
for (int i = n - 1 ; i >= 0 ; i--) {
while (s.Count > 0 && arr[s.Peek()] >= arr[i]){
s.Pop();
}
// The index of next smaller element
// starting from i'th index
int last = (s.Count == 0 ? n : s.Peek());
// Adding the number of subarray which
// can be formed in the range [i, last]
ans += (last - i);
s.Push(i);
}
return ans;
}
// Driver Code
public static void Main(string[] args){
List<int> arr = new List<int>{
1, 3, 5, 2
};
// Function call
Console.Write(countSubarrays(arr));
}
}
// This code is contributed by subhamgoyal2014.
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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Count subarrays for every array element in which they are the minimum Given an array arr[] consisting of N integers, the task is to create an array brr[] of size N where brr[i] represents the count of subarrays in which arr[i] is the smallest element. Examples: Input: arr[] = {3, 2, 4} Output: {1, 3, 1} Explanation: For arr[0], there is only one subarray in which 3 is
15+ min read
Count subarrays for every array element in which they are the minimum | Set 2 Given an array arr[] consisting of N integers, the task is to create an array brr[] of size N where brr[i] represents the count of subarrays in which arr[i] is the smallest element. Examples: Input: arr[] = {3, 2, 4}Output: {1, 3, 1}Explanation: For arr[0], there is only one subarray in which 3 is t
12 min read
Sum of minimum elements of all subarrays Given an array A of n integers. The task is to find the sum of minimum of all possible (contiguous) subarray of A.Examples: Input: A = [3, 1, 2, 4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3, 1], [1, 2], [2, 4], [3, 1, 2], [1, 2, 4], [3, 1, 2, 4]. Minimums are 3, 1, 2, 4, 1, 1, 2,
15+ min read
Minimum common element in all subarrays of size K Given an array arr[] consisting of N distinct integers and a positive integer K, the task is to find the minimum element that occurs in all subarrays of size K. If no such element exists, then print "-1". Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 4Output: 2Explanation:The subarrays of size 4 are
7 min read
Minimum elements to be inserted such that no Subarray has sum 0 Given an array arr[] of N integers such that no element is 0 in that array, the task is to find the minimum number of elements to be inserted such that no subarray of the new array has sum 0. Examples: Input: N = 3, arr[] = {1, -1, 1}Output: 2Explanation: As in the array the sum of first two element
6 min read