Number of Valid Subarrays - Problem

Given an integer array nums, return the number of non-empty subarrays with the leftmost element of the subarray not larger than other elements in the subarray.

A subarray is a contiguous part of an array.

Example: For array [1, 4, 2, 5, 3], the subarray [1, 4, 2] is valid because the leftmost element 1 is not larger than 4 and 2. However, [4, 2] is not valid because 4 > 2.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,2,5,3]
Output: 7
💡 Note: Valid subarrays: [1], [1,4], [1,4,2], [1,4,2,5], [1,4,2,5,3], [4], [5]. The element 1 can extend through the entire array since it's the minimum.
Example 2 — Single Element
$ Input: nums = [3]
Output: 1
💡 Note: Only one subarray [3], which is valid since the leftmost (and only) element is not larger than itself.
Example 3 — Decreasing Array
$ Input: nums = [5,4,3,2,1]
Output: 15
💡 Note: Every possible subarray is valid since each leftmost element is always >= subsequent elements. Total: 5+4+3+2+1 = 15 subarrays.

Constraints

  • 1 ≤ nums.length ≤ 50,000
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Valid Subarrays: Leftmost ≤ All Others1425301234Valid Subarrays (leftmost ≤ all elements):[1] [1,4] [1,4,2] [1,4,2,5] [1,4,2,5,3] — starting with 1[4] — starting with 4 (stops at 2 since 4 > 2)[5] — starting with 5 (stops at 3 since 5 > 3)Total: 7 Valid Subarrays
Understanding the Visualization
1
Input Array
Given array [1,4,2,5,3]
2
Valid Check
Count subarrays where first element ≤ all elements
3
Count Result
Total valid subarrays: 7
Key Takeaway
🎯 Key Insight: Use a monotonic stack to efficiently find the span where each element can serve as the leftmost leader
Asked in
Google 12 Amazon 8 Microsoft 6
12.8K Views
Medium Frequency
~25 min Avg. Time
324 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