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
Difficulty
and has an acceptance rate of about 70% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Simulation
- Stack
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 1175: Prime Arrangements
- problem 967: Numbers With Same Consecutive Differences
- problem 2034: Stock Price Fluctuation
- problem 2375: Construct Smallest Number From DI String
- problem 2443: Sum of Number and Its Reverse
- problem 2521: Distinct Prime Factors of Product of Array
- problem 2601: Prime Subtraction Operation
- problem 2761: Prime Pairs With Target Sum
Extra
- 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