Find the Number of Subarrays Where Boundary Elements Are Maximum - Problem

You are given an array of positive integers nums.

Return the number of subarrays of nums where the first and last elements of the subarray are equal to the largest element in the subarray.

A subarray is a contiguous sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,3,3,2]
Output: 6
💡 Note: Valid subarrays: [1] (first=last=max=1), [4] (first=last=max=4), [3] at index 2, [3] at index 3, [3,3] (first=last=max=3), [2] (first=last=max=2)
Example 2 — All Same Elements
$ Input: nums = [3,3,3]
Output: 6
💡 Note: All elements equal, so all subarrays are valid: [3], [3], [3], [3,3], [3,3], [3,3,3]
Example 3 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Only one subarray [1] where first=last=max=1

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Find Subarrays Where Boundary Elements Are Maximum INPUT Array nums: 1 i=0 4 i=1 3 i=2 3 i=3 2 i=4 Valid Subarrays: [1] at i=0 [4] at i=1 [3] at i=2 [3,3] at i=2,3 [3] at i=3 [2] at i=4 Condition: first = last = max nums = [1,4,3,3,2] ALGORITHM STEPS 1 Use Monotonic Stack Track elements in decreasing order 2 Group Same Values Count occurrences of each value 3 Pop Smaller Elements Remove elements less than current 4 Count Valid Pairs Add count for matching boundaries Stack State Example: (val=4, cnt=1) (val=3, cnt=2) (val=2, cnt=1) O(n) time, O(n) space FINAL RESULT Count Breakdown: [1]: 1 subarray (single) [4]: 1 subarray (single) [3]: 2 singles + 1 pair = 3 [2]: 1 subarray (single) Total = 1 + 1 + 3 + 1 Output: 6 OK - 6 valid subarrays found! Each boundary equals max element Key Insight: Use a monotonic decreasing stack to track (value, count) pairs. When we encounter an element, pop smaller elements (they can't be max), merge equal values (count pairs), and add count to result. For n same values, valid subarrays = n + n*(n-1)/2 (singles + pairs where both ends match). TutorialsPoint - Find the Number of Subarrays Where Boundary Elements Are Maximum | Optimized Two-Pass Solution
Asked in
Google 15 Meta 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen