Problem Description
Given two arrays, pushed and popped, determine if the popped array could be the result of a series of push and pop operations on an initially empty stack. Every element in pushed is unique, and popped is a permutation of pushed.
Key Insights
- Use a stack to simulate the push and pop operations.
- Iterate over the pushed array, pushing each element to the stack.
- After each push, check if the top of the stack equals the current element in the popped array. If so, perform pop operations.
- Continue this process until either all elements are processed or a mismatch occurs.
- The simulation confirms the validity of the popped sequence if the stack is empty at the end.
Space and Time Complexity
Time Complexity: O(n) where n is the number of elements, as each element is pushed and popped at most once. Space Complexity: O(n) for the auxiliary stack used during the simulation.
Solution
We simulate the process using a stack:
- Initialize an empty stack and an index pointer for the popped array.
- Traverse the pushed sequence, pushing each element onto the stack.
- After each push, while the stack is not empty and the element on top of the stack equals the current element in popped (indicated by the index pointer), pop from the stack and increment the pointer.
- If all operations complete and the stack is empty, the sequence is valid; otherwise, it is not. The key trick is continuously comparing the top of the stack with the next element in popped and performing pop operations as long as they match.