Validate Stack Sequences (LeetCode 946): Solution and Explanation
Decide whether a popped order can come from pushing pushed in order onto an empty stack and popping at chosen moments. [1,2,3,4,5] and [4,5,3,2,1] is true, while [4,3,5,1,2] is false.
Intuition
The fastest way to check whether a stack could produce an order is to run a stack. Push values in the given order and see whether pops can follow popped.
The only decision is when to pop. If the top equals the next value popped wants, pop it right away. Any later push would sit on top of it, and it could not come out until that later value left, which would break the order.
So the greedy choice is forced. If after all pushes some values are still stuck on the stack, the order was impossible.
Approach: Greedy simulation
- Start with an empty stack and j = 0, the next index in popped.
- For each x in pushed, push x.
- While the stack is not empty and its top equals popped[j], pop and increase j.
- Return whether j reached the length of popped.
Step-by-step example
pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
- Push 1, 2, 3, 4. The top 4 equals popped[0], so pop it. The top 3 equals popped[1], so pop it.
- The top 2 is not popped[2] = 5. Push 5, and it matches, so pop it.
- Now popped[3] = 1, but the top is 2. Nothing is left to push.
- 1 is buried under 2, so the order is impossible. Return false.
Code: Python, Java, C++
1class Solution:
2 def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
3 stack = []
4 j = 0
5 for x in pushed:
6 stack.append(x)
7 while stack and stack[-1] == popped[j]:
8 stack.pop()
9 j += 1
10 return j == len(popped)1class Solution {
2 public boolean validateStackSequences(int[] pushed, int[] popped) {
3 Deque<Integer> stack = new ArrayDeque<>();
4 int j = 0;
5 for (int x : pushed) {
6 stack.push(x);
7 while (!stack.isEmpty() && stack.peek() == popped[j]) {
8 stack.pop();
9 j++;
10 }
11 }
12 return j == popped.length;
13 }
14}1class Solution {
2public:
3 bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
4 vector<int> st;
5 int j = 0;
6 for (int x : pushed) {
7 st.push_back(x);
8 while (!st.empty() && st.back() == popped[j]) {
9 st.pop_back();
10 j++;
11 }
12 }
13 return j == (int)popped.size();
14 }
15};Time and space complexity
O(n)
Each value is pushed once and popped at most once.
O(n)
The stack can hold all n values when the pops come at the end.
Other approaches
Reuse pushed as the stack (time O(n), space O(1))
Write each pushed value into pushed[size] and treat the prefix pushed[0..size) as the stack. Same greedy logic with O(1) extra space, at the cost of modifying the input.
Common mistakes
- Popping only once after each push. Several pops can be due in a row, so it must be a while loop.
- Reading popped[j] after j reached the end. The stack is empty whenever every value has been popped, so checking the stack first avoids that.
- Trying to search the stack for the needed value. A stack can only remove its top, so a buried value means the answer is false.
Frequently asked questions
Why is popping greedily always correct?
If the top is the next value to pop and you push something instead, that new value covers it. The new value would then have to be popped first, but it comes later in popped, so the order fails. Popping now never hurts.
Can I return false early?
Yes. You can stop once every value is pushed and the top does not match, but checking j at the end gives the same answer with simpler code.