GFG App
Open App
Browser
Continue

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

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 lengthcurrent index is stored.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to find the count of subarrays` `vector<``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 Code` `int` `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

 `// Java program for the above approach` `import` `java.util.ArrayList;`   `class` `GFG {`   `  ``// Function to find the count of subarrays` `  ``static` `ArrayList countOfSubArray(``int``[] arr) {` `    ``int` `next, i, j;` `    ``int` `n = arr.length;` `    ``ArrayList ans = ``new` `ArrayList();`   `    ``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 ans = countOfSubArray(arr);`   `    ``for` `(``int` `i = ``0``; i < ans.size(); i++) {` `      ``System.out.print(ans.get(i) + ``" "``);` `    ``}` `  ``}` `}`   `// This code is contributed by gfgking.`

## Python3

 `# Python code for the above approach`   `# Function to find the count of subarrays` `def` `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 Code` `arr ``=` `[``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#

 `// C# program for the above approach` `using` `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.`

## Javascript

 ``

Output

`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
• 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++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to determine how many count` `// of subarrays are possible` `// with each number` `vector<``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 Code` `int` `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

 `// Java program for the above approach` `import` `java.util.*;` `class` `GFG{`   `// Function to determine how many count` `// of subarrays are possible` `// with each number` `static` `Vector countOfSubArray(``int``[] arr)` `{`   `    ``Stack st = ``new` `Stack();` `  `  `    ``// To store the answer` `    ``Vector v = ``new` `Vector();` `    ``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 Code` `public` `static` `void` `main(String[] args)` `{` `  `  `    ``// Given numbers` `    ``int` `[]arr ={ ``1``, ``4``, ``2``, ``5``, ``3` `};`   `    ``// Function Call` `    ``Vector 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`

## Python3

 `# Python program for the above approach`   `# Function to determine how many count` `# of subarrays are possible` `# with each number` `def` `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 numbers` `arr ``=` `[ ``1``, ``4``, ``2``, ``5``, ``3` `]`   `# Function Call` `ans ``=` `countOfSubArray(arr)`   `# Printing the result` `for` `i ``in` `range``(``len``(ans)):` `    ``print``(ans[i],end ``=` `" "``)` `    `  `# This code is contributed by shinjanpatra`

## C#

 `// C# program for the above approach` `using` `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`

## Javascript

 ``

Output

`5 1 3 1 1 `

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

My Personal Notes arrow_drop_up