10. Subarrays with First Element Minimum
β GFG solution to the Subarrays with First Element Minimum problem: count subarrays where the first element is the minimum using monotonic stack technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an integer array arr[]. Your task is to count the number of subarrays where the first element is the minimum element of that subarray.
A subarray is valid if its first element is not greater than any other element in that subarray.
π Examples
Example 1
Input: arr[] = [1, 2, 1]
Output: 5
Explanation:
All possible subarrays are:
[1], [1, 2], [1, 2, 1], [2], [2, 1], [1]
Valid subarrays are:
[1], [1, 2], [1, 2, 1], [2], [1] β total 5Example 2
Input: arr[] = [1, 3, 5, 2]
Output: 8
Explanation:
Valid subarrays are: [1], [1, 3], [1, 3, 5], [1, 3, 5, 2], [3], [3, 5], [5], [2] β total 8π Constraints
$1 \le \text{arr.size()} \le 5 \times 10^4$
$1 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses a Monotonic Stack traversed from right to left to efficiently determine for each index how far the subarray can extend while keeping the first element as the minimum:
Monotonic Stack (Right to Left)
Key Observation:
For any index
i,arr[i]remains the minimum of subarrayarr[i..j]as long as no element inarr[i+1..j]is strictly less thanarr[i].So we need to find the next index to the right where a strictly smaller element appears β call it
nxt.The number of valid subarrays starting at
iis exactlynxt - i.
Traverse Right to Left:
Maintain an array-based monotonic stack that stores indices in increasing order of their values (from bottom to top).
For each index
i(moving right to left), pop all stack entries whose corresponding values are β₯ arr[i] β those are no longer useful as "next smaller" boundaries.The top of the stack now holds the index of the next element strictly smaller than
arr[i].
Count Contribution:
If the stack is empty, all indices from
iton-1are valid, so addn - i.Otherwise, add
st[top] - i, wherest[top]is the nearest smaller boundary.
Push Current Index:
Push
ionto the stack for future elements to use as their boundary.
Accumulate and Return:
Sum all contributions and return the total count.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as each element is pushed onto and popped from the stack at most once, resulting in a total of at most 2n stack operations across the entire traversal.
Expected Auxiliary Space Complexity: O(n), as the stack can hold at most n indices in the worst case (e.g., a strictly decreasing array where no element is ever popped).
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Standard Stack Approach
π‘ Algorithm Steps:
Traverse array from right to left using a standard STL monotonic stack.
For each index, pop elements from the stack while they are greater than or equal to the current element.
The stack top gives the next strictly smaller element's index β this becomes the right boundary.
Add
(boundary - i)to the answer and push the current index.
π Complexity Analysis:
Time: β±οΈ O(n) β Each element is pushed and popped at most once
Auxiliary Space: πΎ O(n) β Stack can hold up to n elements
β
Why This Approach?
Most readable and standard implementation using STL.
Clear monotonic stack pattern with intuitive variable naming.
Easy to debug and verify correctness.
π 3οΈβ£ Next Smaller Precomputation
π‘ Algorithm Steps:
Precompute the next strictly smaller element's index for each position using a monotonic stack in a separate pass.
Store boundaries in a
nxt[]array; default value isn(meaning no smaller element exists).In a second pass, sum up
nxt[i] - ifor all indices to get the final count.
π Complexity Analysis:
Time: β±οΈ O(n) β Two independent linear passes through the array
Auxiliary Space: πΎ O(n) β Extra
nxt[]array plus the stack
β
Why This Approach?
Cleanly separates the precomputation and accumulation phases.
The
nxt[]array is reusable if boundary information is needed later.Easier to test boundary values individually.
π 4οΈβ£ Greedy Expansion Approach
π‘ Algorithm Steps:
For each starting index
i, greedily extend the subarray to the right.Continue extending as long as the next element is greater than or equal to
arr[i](keepingarr[i]the minimum).Count all valid subarrays that start at
ias(j - i + 1)wherejis the furthest valid index.No extra data structure is needed β direct comparison.
π Complexity Analysis:
Time: β±οΈ O(nΒ²) worst case, O(n) for strictly decreasing sequences
Auxiliary Space: πΎ O(1) β No extra space required
β
Why This Approach?
Simple and intuitive β no stack or extra data structure needed.
Great for understanding the problem from first principles.
Works efficiently in practice for random or nearly decreasing inputs.
β οΈ Note: This approach results in Time Limit Exceeded (TLE) for large inputs near the constraint boundary. (fails ~1010/1120 test cases due to time constraints).
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π·οΈ Array-Based Stack
π’ O(n)
π’ O(n)
π Fastest, cache-friendly
π§ Manual stack management
π Standard Stack
π’ O(n)
π’ O(n)
π Most readable
πΎ STL overhead
π Precomputation
π’ O(n)
π‘ O(n)
π― Clear separation of phases
πΎ Extra array storage
π Greedy Expansion
π‘ O(nΒ²) worst
π’ O(1)
β No extra space, simple logic
π§ Worst case quadratic, TLE risk
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Competitive Programming
π₯ Array-Based Stack
β β β β β
π Readability & Debugging
π₯ Standard Stack
β β β β β
π§ Need Boundary Information
π₯ Precomputation
β β β β β
π― Space Critical / Small Inputs
π Greedy Expansion
β β β ββ
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated