Given two integer arrays
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
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
1 <= pushed.length <= 1000 0 <= pushed[i] <= 1000 - All the elements of
pushed are unique. popped.length == pushed.length popped is a permutation ofpushed .
Contents
Solution 1 - Using stack
In this approach, we are going to use a
Let's look at an example with
![example 1 with pushed = [1, 2, 3, 4, 5] and popped = [4, 5, 3, 2, 1]](/algo/stack/ValidateStackSequences/img/Example1.png)
Implementation steps:
-
First, we will create a variable
pushedStack aStack that we will use to storepushed array elements, and another variablepopIndex that we will use as a pointer to point atpopped array. -
Next, loop through
pushed array and push the elements into thestack , also using awhile loop, check if the top of the stack element and the element atpopIndex frompopped array are same, if they are same keep popping up the elements fromstack . -
Given that, both
pushed andpopped arrays have same elements and they are of same length, by the end of above step, if sequence is valid, then thepushedStack will be empty, since we have popped all elements. -
Finally, check if the stack is empty, if it is empty return
true , otherwise returnfalse .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n).
Above implementations source code can be found at