Number of Valid Subarrays — LeetCode 1063 Python Solution

HardLeetCode PremiumStackArrayMonotonic Stack
Problem
#1063
Pattern
Stack
Reading time
2 min

The 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

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].

Python solution

Python
class Solution:
    def validSubarrays(self, nums: List[int]) -> int:
        n = len(nums)
        right = [n] * n
        stk = []
        for i in range(n - 1, -1, -1):
            while stk and nums[stk[-1]] >= nums[i]:
                stk.pop()
            if stk:
                right[i] = stk[-1]
            stk.append(i)
        return sum(j - i for i, j in enumerate(right))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1063. Number of Valid Subarrays is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1063. Number of Valid Subarrays?
LeetCode 1063. Number of Valid Subarrays is rated Hard on LeetCode.
What is the time complexity of LeetCode 1063. Number of Valid Subarrays?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1063. Number of Valid Subarrays?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1063. Number of Valid Subarrays cover?
LeetCode 1063. Number of Valid Subarrays is tagged Stack, Array and Monotonic Stack on LeetCode.
Is LeetCode 1063. Number of Valid Subarrays a premium problem?
Yes. LeetCode 1063. Number of Valid Subarrays is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview