Validate Stack Sequences — LeetCode 946 Python Solution

MediumStackArraySimulation
Problem
#946
Pattern
Stack
Reading time
2 min

The problem

Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.

Example

Input
pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output
true
Explanation
We might do the following sequence:

Python solution

Python
class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        stk = []
        i = 0
        for x in pushed:
            stk.append(x)
            while stk and stk[-1] == popped[i]:
                stk.pop()
                i += 1
        return i == len(popped)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 946. Validate Stack Sequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

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 946. Validate Stack Sequences?
LeetCode 946. Validate Stack Sequences is rated Medium on LeetCode.
What is the time complexity of LeetCode 946. Validate Stack Sequences?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 946. Validate Stack Sequences?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 946. Validate Stack Sequences cover?
LeetCode 946. Validate Stack Sequences is tagged Stack, Array and Simulation on LeetCode.

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