Open In App

Count subarrays for every array element in which they are the minimum

Last Updated : 15 Jul, 2025
Comments
Improve
Suggest changes
1 Like
Like
Report

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 the smallest({3}). 
For arr[1], there are three such subarrays where 2 is the smallest({2}, {3, 2}, {2, 4}). 
For arr[2], there is only one subarray in which 4 is the smallest({4}).

Input: arr[] = {1, 2, 3, 4, 5} 
Output: {5, 4, 3, 2, 1}

Naive Approach: The simplest approach is to generate all subarrays of the given array and while generating the subarray, find the element which is minimum in that subarray and then store the index of that element, then later increment count for that index by 1. Similarly, do this for every subarray

Code-

C++
Java Python3 C# JavaScript

Output
[1, 4, 1, 8, 1]

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

Efficient Approach: To optimize the above approach, the idea is to find the boundary index for every element, up to which it is the smallest element. For each element let L and R be the boundary indices on the left and right side respectively up to which arr[i] is the minimum. Therefore, the count of all subarrays can be calculated by:

(L + R + 1)*(R + 1)

Follow the steps below to solve the problem:

  1. Store all the indices of array elements in a Map.
  2. Sort the array in increasing order.
  3. Initialize an array boundary[].
  4. Iterate over the sorted array arr[] and simply insert the index of that element using Binary Search. Suppose it got inserted at index i, then its left boundary is boundary[i – 1] and its right boundary is boundary[i + 1].
  5. Now, using the above formula, find the number of subarrays and keep track of that count in the resultant array.
  6. After completing the above steps, print all the counts stored in the resultant array.

Below is the implementation of the above approach:

C++14
Java Python3 C# JavaScript

Output
[1, 4, 1, 8, 1]

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

Most efficient approach:   

To optimize the above approach we can use a Stack Data Structure.

  1. Idea is that, For each (1? i ? N) we will try to find index(R) of next smaller element right to it  and index(L) of next smaller element left to it.
  2. Now we have our boundary index(L,R) in which arr[i] is minimum so total number of subarrays for each i(0-base) will be (R-i)*(i-L) .

Below is the implementation of the idea:

C++14
Java Python3 C# JavaScript

Output
[1, 4, 1, 8, 1]

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


Practice Tags :

Similar Reads