946. Validate Stack Sequences
Last updated
Last updated
/**
* Time complexity : O(N), where N is the length of pushed and popped.
* Space complexity : O(N)
*/
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int N = pushed.length;
Stack<Integer> stack = new Stack();
int j = 0;
for (int x: pushed) {
stack.push(x);
while (!stack.isEmpty() && j < N && stack.peek() == popped[j]) {
stack.pop();
j++;
}
}
return j == N;
}
}/**
* Time complexity : O(N), where N is the length of pushed and popped.
* Space complexity : O(1)
*/
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int n = pushed.length, top = 0;
for(int pushIdx = 0, popIdx = 0; pushIdx < n; pushIdx++) {
// Push kth element to stack
pushed[top] = pushed[pushIdx];
// Pop if element match
while(top >= 0 && pushed[top] == popped[popIdx]) {
top--;
popIdx++;
}
top++;
}
return top == 0;
}
}