We can simulate the actual push and pop operations on a stack to verify if the sequences are valid. The key insight is that whenever we push an element, we should immediately try to pop as many elements as possible that match the expected pop sequence. If the simulation completes with an empty stack, the sequences are valid.
i to track position in the popped array.pushed array and push it onto the stack.popped (at index i).i.true if the stack is empty, indicating all elements were successfully popped in the correct order.Instead of using a separate stack, we can reuse the pushed array itself as the stack. The left portion of the array acts as our stack, eliminating the need for extra space. This works because as we process elements, we overwrite positions that are no longer needed.
l represents the top of our simulated stack within pushed, and r tracks position in popped.pushed and write it to position l, then increment l.l-1 matches popped[r].l > 0, increment r and decrement l to simulate popping.pushed.true if l equals 0, meaning all elements were successfully matched and popped.