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: 11
💡 Note: Valid subarrays: Starting from index 0: [1], [1,4], [1,4,2], [1,4,2,5], [1,4,2,5,3] (5 total). Starting from index 1: [4] (1 total). Starting from index 2: [2], [2,5], [2,5,3] (3 total). Starting from index 3: [5] (1 total). Starting from index 4: [3] (1 total). Total: 5+1+3+1+1 = 11.
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
Number of Valid Subarrays INPUT Array nums: 1 i=0 4 i=1 2 i=2 5 i=3 3 i=4 Valid Subarrays: [1] - leftmost: 1 [1,4] - leftmost: 1 [1,4,2] - leftmost: 1 [1,4,2,5] - leftmost: 1 [1,4,2,5,3] - leftmost: 1 [4] - leftmost: 4 [2] - leftmost: 2 [2,5] - leftmost: 2 [5] - leftmost: 5 [3] - leftmost: 3 7 valid subarrays total ALGORITHM STEPS 1 Use Monotonic Stack Stack stores indices in increasing order of values 2 For Each Element Pop elements from stack while top > current 3 Count Valid Subarrays When popping index j, count += (i - j) subarrays 4 Process Remaining Pop remaining and add (n - index) for each Stack Operations Example: i=0: push(0), stack=[0] i=1: push(1), stack=[0,1] i=2: pop(1), count+=1 push(2), stack=[0,2] i=3: push(3), stack=[0,2,3] i=4: pop(3), count+=1, ... FINAL RESULT Output: 7 Valid Subarrays Count Count Breakdown: Starting at index 0: 5 subarrays (n-0=5) Starting at index 1: 1 subarray (ends at 2) Starting at index 2: 0 (handled in count) Remaining elements: +1 more = 7 total Key Insight: Use a monotonic increasing stack to track potential subarray start indices. When we find a smaller element, pop indices where the value is greater. The number of valid subarrays starting at popped index j is (current_index - j). Time Complexity: O(n), Space Complexity: O(n) TutorialsPoint - Number of Valid Subarrays | Optimal Solution (Monotonic Stack)
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