Number of Valid Subarrays Problem
Description
LeetCode Problem 1063.
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 1:
Input: nums = [1,4,2,5,3]
Output: 11
Explanation: There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].
Example 2:
Input: nums = [3,2,1]
Output: 3
Explanation: The 3 valid subarrays are: [3],[2],[1].
Example 3:
Input: nums = [2,2,2]
Output: 6
Explanation: There are 6 valid subarrays: [2],[2],[2],[2,2],[2,2],[2,2,2].
Constraints:
1 <= nums.length <= 5 * 10^40 <= nums[i] <= 10^5
Solution
Approach: Monotonic Stack
Count the valid subarrays by where they end. A subarray nums[j..i] is valid when nums[j] is not larger than anything in nums[j + 1..i]. Call such a j a valid start for i.
Keep the valid starts for the current i on a stack. When the next value x arrives:
- every start with a value larger than
xstops being valid, and it can never become valid again, becausexstays inside every longer subarray from that start. Pop those; - the remaining starts all have values
<= x, so they stay valid; xitself starts the one-element subarray[x], so push it.
The stack now holds exactly the valid starts for subarrays ending at x, and we add its size to the answer. The values on the stack never decrease from bottom to top, so the larger values are always on top, where we pop them.
Note the comparison is strict: equal values do not pop each other, since [2, 2] is valid. With [2, 2, 2] the stack grows to sizes 1, 2, 3, giving 6.
Complexity: O(n) time, since each element is pushed and popped at most once, and O(n) extra space.
class Solution:
def validSubarrays(self, nums: List[int]) -> int:
# The stack holds the values that are still valid left ends: each one is
# not larger than anything after it, so the stack is non-decreasing.
stack = []
ans = 0
for x in nums:
while stack and stack[-1] > x:
stack.pop() # a larger left end can never be valid again
stack.append(x)
ans += len(stack) # valid subarrays that end at x
return ans