Count of subarrays for each Array element in which arr[i] is first and least - GeeksforGeeks

04 Apr, 2022
Given an array arr[], the task is to find the count of subarrays starting from the current element that has a minimum element as the current element itself.
Examples: 
Input: arr[] = {2, 4, 2, 1, 3} Output: {3, 1, 1, 2, 1}Explanation: For the first element we can form 3 valid subarrays with the given condition 
2 -> {2} , {2,4} , {2,4,2} = 3 subarrays and so on
4 -> {4}                   = 1 subarray
2 -> {2}                   = 1 subarray
1 -> {1} , {1, 3}          = 2 subarrays
3 -> {3}                   = 1 subarray
Input: arr[] = {1, 4, 2, 5, 3}Output: {5, 1, 3, 1, 1}
Naive Solution: The naive approach revolves around the idea that:
If smaller element is not found then count of subarrays = length of array – current index
If element is found then count of subarrays = index of smaller element – current index
The task can be solved using 2 loops. The outer loop picks all the elements one by one. The inner loop looks for the first smaller element for the element picked by the outer loop. If a smaller element is found then the index of that element  – current index is stored as next, otherwise, the length – current index is stored.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of subarraysvector<int> countOfSubArray(vector<int> arr){    int next, i, j;    int n = arr.size();    vector<int> ans;     for (i = 0; i < n; i++) {        bool flag = false;         // If the next smaller element        // is not found then        // length - current index        // would be the answer        next = n - i;        for (j = i + 1; j < n; j++) {            if (arr[i] > arr[j]) {                 // If the next smaller                // element is found then                // the difference of indices                // will be the count                next = j - i;                ans.push_back(next);                flag = true;                break;            }        }         if (flag == false) {            ans.push_back(next);        }    }    return ans;} // Driver Codeint main(){    vector<int> arr{ 1, 4, 2, 5, 3 };     vector<int> ans = countOfSubArray(arr);     for (int i = 0; i < ans.size(); i++) {        cout << ans[i] << " ";    }     return 0;}
// Java program for the above approachimport java.util.ArrayList; class GFG {   // Function to find the count of subarrays  static ArrayList<Integer> countOfSubArray(int[] arr) {    int next, i, j;    int n = arr.length;    ArrayList<Integer> ans = new ArrayList<Integer>();     for (i = 0; i < n; i++) {      boolean flag = false;       // If the next smaller element      // is not found then      // length - current index      // would be the answer      next = n - i;      for (j = i + 1; j < n; j++) {        if (arr[i] > arr[j]) {           // If the next smaller          // element is found then          // the difference of indices          // will be the count          next = j - i;          ans.add(next);          flag = true;          break;        }      }       if (flag == false) {        ans.add(next);      }    }    return ans;  }   // Driver Code  public static void main(String args[])  {    int[] arr = { 1, 4, 2, 5, 3 };    ArrayList<Integer> ans = countOfSubArray(arr);     for (int i = 0; i < ans.size(); i++) {      System.out.print(ans.get(i) + " ");    }  }} // This code is contributed by gfgking.
# Python code for the above approach # Function to find the count of subarraysdef countOfSubArray(arr):    n = len(arr)    ans = []     for i in range(n):        flag = 0         # If the next smaller element        # is not found then        # length - current index        # would be the answer        next = n - i        for j in range(i + 1, n):            if arr[i] > arr[j]:                 # If the next smaller                # element is found then                # the difference of indices                # will be the count                next = j - i                ans.append(next)                flag = 1                break         if flag == 0:            ans.append(next)     return ans  # Driver Codearr = [1, 4, 2, 5, 3]ans = countOfSubArray(arr) for i in range(len(ans)):    print(ans[i], end = " ") # This code is contributed by Potta Lokesh
// C# program for the above approachusing System;using System.Collections.Generic; class GFG {   // Function to find the count of subarrays  static List<int> countOfSubArray(int[] arr)  {    int next, i, j;    int n = arr.Length;    List<int> ans = new List<int>();     for (i = 0; i < n; i++) {      bool flag = false;       // If the next smaller element      // is not found then      // length - current index      // would be the answer      next = n - i;      for (j = i + 1; j < n; j++) {        if (arr[i] > arr[j]) {           // If the next smaller          // element is found then          // the difference of indices          // will be the count          next = j - i;          ans.Add(next);          flag = true;          break;        }      }       if (flag == false) {        ans.Add(next);      }    }    return ans;  }   // Driver Code  public static void Main()  {    int[] arr = { 1, 4, 2, 5, 3 };    List<int> ans = countOfSubArray(arr);     for (int i = 0; i < ans.Count; i++) {      Console.Write(ans[i] + " ");    }  }} // This code is contributed by ukasp.
<script>    // JavaScript program for the above approach     // Function to find the count of subarrays    const countOfSubArray = (arr) => {        let next, i, j;        let n = arr.length;        let ans = [];         for (i = 0; i < n; i++) {            let flag = false;             // If the next smaller element            // is not found then            // length - current index            // would be the answer            next = n - i;            for (j = i + 1; j < n; j++) {                if (arr[i] > arr[j]) {                     // If the next smaller                    // element is found then                    // the difference of indices                    // will be the count                    next = j - i;                    ans.push(next);                    flag = true;                    break;                }            }             if (flag == false) {                ans.push(next);            }        }        return ans;    }     // Driver Code    let arr = [1, 4, 2, 5, 3];    let ans = countOfSubArray(arr);     for (let i = 0; i < ans.length; i++) {        document.write(`${ans[i]} `);    } // This code is contributed by rakeshsahni </script>
  
5 1 3 1 1 
 
Time Complexity: O(N2) Auxiliary Space: O(1)
 
Efficient Solution: This problem basically asks to find how far is the current index from the index of the next smaller number to the number at the current index. The most optimal way to solve this problem is by making use of a stack.Follow the below steps to solve the problem:
 
Iterate over each number of the given array arr[] using the current index.
If the stack is empty, push the current index to the stack.
If the stack is not empty then do the following:If the number at the current index is lesser than the number of the index at top of the stack, push the current index.If the number at the current index is greater than the number of the index at top of the stack, then update the count of subarrays as the index at top of the stack – current index
If the number at the current index is lesser than the number of the index at top of the stack, push the current index.
If the number at the current index is greater than the number of the index at top of the stack, then update the count of subarrays as the index at top of the stack – current index
Pop the stack once the number of days has been updated in the output list.
Repeat the above steps for all the indices in the stack that are greater than the number at the current index.
 
Below is the implementation of the above approach:
 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to determine how many count// of subarrays are possible// with each numbervector<int> countOfSubArray(vector<int> arr){     stack<int> st;    // To store the answer    vector<int> v;    int n = arr.size();     // Traverse all the numbers    for (int i = n - 1; i >= 0; i--) {         // Check if current index is the        // next smaller element of        // any previous indices        while (st.size() > 0               && arr[st.top()] >= arr[i]) {            // Pop the element            st.pop();        }         if (st.size() == 0) {            v.push_back(n - i);        }        else {            v.push_back(st.top() - i);        }         // Push the current index        st.push(i);    }    // reverse the output    reverse(v.begin(), v.end());    return v;} // Driver Codeint main(){    // Given numbers    vector<int> arr{ 1, 4, 2, 5, 3 };     // Function Call    vector<int> ans = countOfSubArray(arr);     // Printing the result    for (int i = 0; i < ans.size(); i++) {        cout << ans[i] << " ";    }     return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to determine how many count// of subarrays are possible// with each numberstatic Vector<Integer> countOfSubArray(int[] arr){     Stack<Integer> st = new Stack<Integer>();       // To store the answer    Vector<Integer> v = new Vector<Integer>();    int n = arr.length;     // Traverse all the numbers    for (int i = n - 1; i >= 0; i--) {         // Check if current index is the        // next smaller element of        // any previous indices        while (st.size() > 0               && arr[st.peek()] >= arr[i])        {                       // Pop the element            st.pop();        }         if (st.size() == 0) {            v.add(n - i);        }        else {            v.add(st.peek() - i);        }         // Push the current index        st.add(i);    }       // reverse the output    Collections.reverse(v);    return v;} // Driver Codepublic static void main(String[] args){       // Given numbers    int []arr ={ 1, 4, 2, 5, 3 };     // Function Call    Vector<Integer> ans = countOfSubArray(arr);     // Printing the result    for (int i = 0; i < ans.size(); i++) {        System.out.print(ans.get(i)+ " ");    } }} // This code is contributed by shikhasingrajput
# Python program for the above approach # Function to determine how many count# of subarrays are possible# with each numberdef countOfSubArray(arr):    st = []         # To store the answer    v = []    n = len(arr)     # Traverse all the numbers    for i in range(n - 1,-1,-1):         # Check if current index is the        # next smaller element of        # any previous indices        while len(st) > 0  and arr[st[len(st)-1]] >= arr[i] :            # Pop the element            st.pop()         if (len(st) == 0):            v.append(n - i)        else:            v.append(st[len(st) - 1]- i)         # Push the current index        st.append(i)     # reverse the output    v = v[::-1]    return v # Driver Code # Given numbersarr = [ 1, 4, 2, 5, 3 ] # Function Callans = countOfSubArray(arr) # Printing the resultfor i in range(len(ans)):    print(ans[i],end = " ")     # This code is contributed by shinjanpatra
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{   // Function to determine how many count  // of subarrays are possible  // with each number  static List<int> countOfSubArray(int[] arr)  {     Stack<int> st = new Stack<int>();     // To store the answer    List<int> v = new List<int>();    int n = arr.Length;     // Traverse all the numbers    for (int i = n - 1; i >= 0; i--) {       // Check if current index is the      // next smaller element of      // any previous indices      while (st.Count > 0             && arr[st.Peek()] >= arr[i])      {         // Pop the element        st.Pop();      }       if (st.Count == 0) {        v.Add(n - i);      }      else {        v.Add(st.Peek() - i);      }       // Push the current index      st.Push(i);    }     // reverse the output    v.Reverse();    return v;  }   // Driver Code  public static void Main(String[] args)  {     // Given numbers    int []arr ={ 1, 4, 2, 5, 3 };     // Function Call    List<int> ans = countOfSubArray(arr);     // Printing the result    for (int i = 0; i < ans.Count; i++) {      Console.Write(ans[i]+ " ");    }  }} // This code is contributed by 29AjayKumar
<script> // JavaScript program for the above approach // Function to determine how many count// of subarrays are possible// with each numberfunction countOfSubArray(arr){     let st = [];         // To store the answer    let v = [];    let n = arr.length;     // Traverse all the numbers    for (let i = n - 1; i >= 0; i--) {         // Check if current index is the        // next smaller element of        // any previous indices        while (st.length > 0               && arr[st[st.length-1]] >= arr[i])        {                     // Pop the element            st.pop();        }         if (st.length == 0) {            v.push(n - i);        }        else {            v.push(st[st.length - 1]- i);        }         // Push the current index        st.push(i);    }         // reverse the output    v.reverse();    return v;} // Driver Code // Given numberslet arr = [ 1, 4, 2, 5, 3 ]; // Function Calllet ans = countOfSubArray(arr); // Printing the resultfor (let i = 0; i < ans.length; i++) {    document.write(ans[i]," ");} // This code is contributed by shinjanpatra </script>
  
5 1 3 1 1 
 
Time Complexity: O(N)  Auxiliary Space: O(N) 
 
rakeshsahni
lokeshpotta20
gfgking
ukasp
shikhasingrajput
29AjayKumar
sagartomar9927
shinjanpatra
Algo-Geek 2021
subarray
Algo Geek
Arrays
Stack
Arrays
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Check if given matrix is Zero Division matrix
Check if all duplicate elements in the Array are adjacent or not
Find Characteristic Polynomial of a Square Matrix
Find all substrings containing exactly K unique vowels
Calculate the sum of sum of numbers in range L to R
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews