Number of Valid Subarrays - Problem

You are given an integer array nums. A valid subarray is defined as a contiguous portion of the array where the leftmost element is not larger than any other element in that subarray.

Your task is to count how many such valid subarrays exist in the given array.

Example: In array [3, 4, 1, 5], the subarray [3, 4] is valid because 3 โ‰ค 3 and 3 โ‰ค 4. However, [4, 1] is not valid because 4 > 1.

Goal: Return the total count of all valid subarrays in the input array.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 4, 2, 5, 3]
โ€บ Output: 11
๐Ÿ’ก Note: Valid subarrays: [1], [1,4], [1,4,2], [1,4,2,5], [1,4,2,5,3], [4], [4,5], [2], [2,5], [5], [3]. The leftmost element in each subarray is not larger than any other element in that subarray.
example_2.py โ€” Decreasing Array
$ Input: [3, 2, 1]
โ€บ Output: 3
๐Ÿ’ก Note: Only single-element subarrays are valid: [3], [2], [1]. Any multi-element subarray would have a leftmost element larger than some element to its right.
example_3.py โ€” Increasing Array
$ Input: [1, 2, 3]
โ€บ Output: 6
๐Ÿ’ก Note: All possible subarrays are valid: [1], [1,2], [1,2,3], [2], [2,3], [3]. In an increasing array, every subarray satisfies the condition.

Constraints

  • 1 โ‰ค nums.length โ‰ค 5 ร— 104
  • 1 โ‰ค nums[i] โ‰ค 105
  • Follow-up: Can you solve this in O(n) time complexity?

Visualization

Tap to expand
Valid Team Formations: [1, 4, 2, 5, 3]Leader at position 0 (value=1):1Leader4253Valid teams: [1], [1,4], [1,4,2], [1,4,2,5], [1,4,2,5,3] = 4 teamsLeader at position 1 (value=4):4Leader2Breaks!Valid teams: [4] only = 1 teamMonotonic Stack Insight:โ€ข For each position, find the next smaller elementโ€ข Count valid subarrays = distance to next smaller elementโ€ข Position 0: next smaller at position โˆž โ†’ 5 teamsโ€ข Position 1: next smaller at position 2 โ†’ 1 teamโ€ข Position 2: next smaller at position โˆž โ†’ 2 teamsโ€ข And so on...๐ŸŽฏ Key Insight: Use monotonic stack to efficiently find "breaking points"
Understanding the Visualization
1
Choose a Leader
Each array position can be a potential team leader
2
Extend the Team
Keep adding team members as long as leader โ‰ค all members
3
Count Valid Teams
Use monotonic stack to efficiently count all valid team formations
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking each subarray individually, use a monotonic stack to find where each "leadership chain" breaks, allowing O(n) solution.
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 22
42.8K Views
High Frequency
~25 min Avg. Time
1.3K 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