VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-subarrays-whose-first-element-is-the-minimum/

⇱ Count Subarrays with First Element as Minimum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Subarrays with First Element as Minimum

Last Updated : 15 Sep, 2025

Given an array arr[], 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] With Recalculated Minimum - O(n3) Time and O(1) Space

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.


Output
8

[Better Approach] With Running Minimum - O(n2) Time and O(1) Space

We don’t need to find the minimum separately after two loops. While expanding the subarray, we can directly maintain the running minimum and check if it stays β‰₯ the first element.


Output
8

[Efficient Approach] Using stack - O(n) Time and O(n) Space

The efficient approach is based on the concept of finding the next smaller element on the right of an element.

Working:

  • 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.

Output
8
Comment