Validate Stack Sequences

medium stack simulation array

Problem

Given two integer sequences pushed and popped, each a permutation of the same distinct values, return true if and only if this could be the result of a sequence of push and pop operations on an initially empty stack.

Inputpushed = [1, 2, 3, 4, 5], popped = [4, 5, 3, 2, 1]
Outputtrue
Push 1,2,3,4 then pop 4, push 5 then pop 5, then pop 3,2,1 in order.

def validate_stack_sequences(pushed, popped):
    stack = []
    j = 0
    for x in pushed:
        stack.append(x)
        while stack and j < len(popped) and stack[-1] == popped[j]:
            stack.pop()
            j += 1
    return j == len(popped)
function validateStackSequences(pushed, popped) {
  const stack = [];
  let j = 0;
  for (const x of pushed) {
    stack.push(x);
    while (stack.length && j < popped.length && stack[stack.length - 1] === popped[j]) {
      stack.pop();
      j++;
    }
  }
  return j === popped.length;
}
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Deque<Integer> stack = new ArrayDeque<>();
        int j = 0;
        for (int x : pushed) {
            stack.push(x);
            while (!stack.isEmpty() && j < popped.length && stack.peek() == popped[j]) {
                stack.pop();
                j++;
            }
        }
        return j == popped.length;
    }
}
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
    stack<int> st;
    int j = 0;
    for (int x : pushed) {
        st.push(x);
        while (!st.empty() && j < (int)popped.size() && st.top() == popped[j]) {
            st.pop();
            j++;
        }
    }
    return j == (int)popped.size();
}
Time: O(n) Space: O(n)