Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Stack
The idea is to simulate the push and pop operations using a stack. We iterate through the pushed
array and perform push operations. For each pushed value, we check if it matches the current value in popped
. If it matches, we perform a pop operation and move to the next value in the popped
array. This process continues until we have processed all elements in both arrays.
Here is the approach:
- Use a stack to simulate the push and pop operations.
- Iterate over the
pushed
array and push elements onto the stack. - After each push, check if the top of the stack matches the current value in
popped
. - If it matches, pop the stack and move to the next value in
popped
. - Repeat the process until all elements in
pushed
are processed. - Finally, check if the stack is empty. If the stack is empty, the sequences are valid; otherwise, they are not.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of thepushed
array, as each element is pushed and popped at most once. - 🧺 Space complexity:
O(n)
for storing elements in the stack.