HardNo. 1063LeetCode Premium

Number of Valid Subarrays — LeetCode 1063 Python Solution

Pattern
Stack
Topics
Stack, Array, Monotonic 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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0084Largest Rectangle in HistogramHard
0456132 PatternMedium
0503Next Greater Element IIMedium
0654Maximum Binary TreeMedium
0739Daily TemperaturesMedium
0853Car FleetMedium

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.

Free to download. Check it runs on your machine, then pick a plan.