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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code