package leetcode;

/**
 * https://leetcode.com/problems/validate-stack-sequences/
 */
public class Problem946 {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        // TODO
        return false;
    }

    public static void main(String[] args) {
        Problem946 prob = new Problem946();
        System.out.println(prob.validateStackSequences(
            new int[]{1, 2, 3, 4, 5}, new int[]{4, 5, 3, 2, 1}
        )); // true
        System.out.println(prob.validateStackSequences(
            new int[]{1, 2, 3, 4, 5}, new int[]{4, 3, 5, 1, 2}
        )); // false
    }
}

package leetcode;

import java.util.Stack;

/**
 * https://leetcode.com/problems/validate-stack-sequences/
 */
public class Problem946 {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        if (pushed.length == 0 || popped.length == 0) {
            return true;
        }
        Stack<Integer> stack = new Stack<>();
        int pushIdx = 0;
        int popIdx = 0;
        stack.push(pushed[pushIdx++]);
        while (pushIdx < pushed.length && popIdx < popped.length) {
            if (!stack.isEmpty() && stack.peek() == popped[popIdx]) {
                popIdx++;
                stack.pop();
            } else {
                stack.push(pushed[pushIdx++]);
            }
        }
        while (!stack.isEmpty()) {
            if (stack.peek() != popped[popIdx]) {
                return false;
            }
            popIdx++;
            stack.pop();
        }
        return true;
    }
}

Solve problem 946