Problem 946

Abstract / Summary

Check if one sequence of pops can be made from another sequence of pushes using a stack.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0946.py

class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        # removing at the end is much faster
        popped.reverse()

        s = []
        for p in pushed:
            # add one element and try to remove as many as possible
            s.append(p)
            while s and s[-1] == popped[-1]:
                s.pop()
                popped.pop()

        return not popped
14 lines | 442 bytes | submitted September 26, 2023 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Simulation
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether a given popped sequence can be produced by a stack that receives the elements of pushed in order. It simulates the stack operations using an auxiliary list s and processes the popped list from the end, which allows constant-time removal of the next expected element. The algorithm returns True when the simulated stack can be emptied exactly as described by popped, otherwise it returns False.

Key Steps

The algorithm consists of three distinct phases: preparation of the popped list, iterative simulation of push and pop operations, and final verification.

Preparation of the popped list

The code reverses the popped list so that the element to be matched next resides at the end of the list. Removing the last element of a Python list is an O(1) operation, which is faster than removing from the front.

popped.reverse()

Iterative simulation

The main loop iterates over each element p in pushed. For each element the algorithm pushes it onto the simulated stack s. After each push it attempts to pop as many elements as possible by comparing the top of s with the last element of popped. When they match, both the simulated stack and the popped list are reduced.

s = []
for p in pushed:
    s.append(p)
    while s and s[-1] == popped[-1]:
        s.pop()
        popped.pop()

Final verification

When the loop finishes, the algorithm checks whether any elements remain in popped. An empty popped list indicates that every expected pop was successfully matched, so the function returns True. If any elements remain, the function returns False.

return not popped

Edge Cases Handled

The code correctly processes scenarios where the pushed and popped sequences are empty. Reversing an empty list yields another empty list, and the final return not popped evaluates to True, reflecting that an empty sequence is trivially valid.

When the popped sequence contains elements that never appear at the top of the simulated stack, the inner while loop never executes for those elements. The algorithm proceeds through all pushes, and the leftover elements in popped cause the final check to return False. This covers cases where the popped order is incompatible with any stack behavior.

If the popped sequence is a perfect reverse of pushed, each newly pushed element is immediately popped. The inner loop removes the element right after it is added, leaving the simulated stack empty throughout the iteration. The algorithm still returns True because popped becomes empty after the final iteration.

When duplicate values appear in the sequences, the algorithm relies on the order of operations rather than value uniqueness. The comparison s[-1] == popped[-1] ensures that only the correct instance of a duplicate value is matched at the appropriate time, handling cases with repeated numbers correctly.

Performance Optimizations

The most notable optimization is the reversal of the popped list. By converting the problem of removing the first element into removing the last element, the code leverages the fact that list.pop() without an index runs in constant time. This eliminates the overhead associated with pop(0), which would require shifting all remaining elements.

The inner while loop is designed to pop as many matching elements as possible after each push. This reduces the number of iterations needed to process the sequences, because multiple consecutive pops are handled in a single pass rather than waiting for additional pushes.

Using a plain Python list s as the simulated stack provides fast append and pop operations, both of which are amortized O(1). The algorithm avoids any additional data structures or function calls that could introduce unnecessary overhead.

Overall, the combination of list reversal, in-place popping, and tight loop control results in a solution that operates efficiently for large input sizes while maintaining clear and concise logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a stack of colorful blocks. The code starts by looking at a list of numbers that tell you which order to stack the blocks, and another list that tells you which order to take them back off. First, the instructions are turned around so it is easier to read them from the end. Then, a new empty space is set up to hold the blocks while they wait.

As each block comes in, it gets placed onto the pile. Right after a block is added, the code checks to see if it matches the next block in the instructions for taking them off. If the block at the top of the pile matches the block that needs to be removed, it gets taken off, and the pile gets a little smaller. This keeps happening over and over again, adding blocks and checking if they can be removed, until all the blocks have been handled. If the pile is empty at the very end, it means everything matched perfectly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.67 | σ = 1.63

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS C# Go Rust TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JS
fartem Ruby
fengvyi C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
martianoff Scala
qiyuangong Java
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
fengvyi C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
martianoff Scala
qiyuangong Java
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
44 links | 27 authors | 10 languages

Videos

12 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

9 solutions   September 26, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality