[LeetCode][946. Validate Stack Sequences] 4 Approaches: Stack, Array and Greedy
By Long Luo
This article is the solution 4 Approaches: Stack, Array, Greedy and O(n) Time O(1) Space of Problem 946. Validate Stack Sequences.
Intuition
All elements must be pushed in in order. The key is how to pop them out?
Assuming that the value of the current top element of the stack is \(1\), and the next value to be popped in the corresponding popped sequence is also \(1\), then this value must be popped out immediately. Because the subsequent push will change the top element of the stack to a value other than \(2\), so the popped sequence of the popped numbers does not correspond.
Pushes each number in the pushed queue onto the stack, checking to see if the number is the next value to be popped in the popped sequence, and pops it if so.
Finally, check that not all the popped values are popped.
Stack
We can use a Stack to simulate the process.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public boolean validateStackSequences(int[] pushed, int[] popped) {
if (popped == null || pushed.length <= 1) {
return true;
}
int len = pushed.length;
int popIdx = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < len; i++) {
stack.push(pushed[i]);
while (!stack.empty() && popIdx < len && stack.peek() == popped[popIdx]) {
stack.pop();
popIdx++;
}
}
return popIdx == len;
}
Analysis
- Time Complexity: \(O(N)\)
- Space Complexity: \(O(N)\)