Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:

Contents

In this approach, we are going to use a Stack to push element from pushed array, and when the elements from popped started matching, then pop eleemnts from the stack.

Let's look at an example with pushed = [1, 2, 3, 4, 5] and popped = [4, 5, 3, 2, 1]

example 1 with pushed = [1, 2, 3, 4, 5] and popped = [4, 5, 3, 2, 1]
Implementation steps:
import java.util.Stack; public class ValidateStackSequences { static boolean validateStackSequences(int[] pushed, int[] popped) { Stack<Integer> stackPushed = new Stack<>(); int popIndex = 0; for(int pushElement: pushed) { // 2, 1, 0 --- 1, 2, 0 ==> true stackPushed.push(pushElement); while(!stackPushed.isEmpty() && popIndex<popped.length && stackPushed.peek() == popped[popIndex]) { stackPushed.pop(); popIndex++; } } return stackPushed.isEmpty(); } public static void main(String[] args) { System.out.println(validateStackSequences(new int[]{1,2,3}, new int[]{3,2,1})); System.out.println(validateStackSequences(new int[]{1,2,3,4,5}, new int[]{4,5,3,2,1})); System.out.println(validateStackSequences(new int[]{1,2,3,4,5}, new int[]{4,3,5,1,2})); System.out.println(validateStackSequences(new int[]{2,1,0}, new int[]{1,2,0})); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of input array pushed.
Space complexity: O(n).

Above implementations source code can be found at GitHub link for Java code