Skip to content

Validate Stack Sequences

Leetcode 946. Validate Stack Sequences

Leetcode 946. Validate Stack Sequences

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.

Example 1:

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

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
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 of pushed.

Source : Leetcode 946. Validate Stack Sequences

Solution

We need to validate a sequence of push and pop in a stack. The push sequence is given and also the pop sequence. Now, the question is which one should be popped after one or more push, right?

One straight forward solution could be to do permutations of push and pop sequences. For example, we can push the first element of pushed array (see below image of pushed and popped arrays) and then try to pop that element from stack and put that in a separate array. Or we can push the second element instead and pop.

This will give us a solution but will take a lot of computational effort.

What if we push an element from pushed array and see if that element is the first element of the popped array? If that is, we can move towards the second element (of popped array), pop the stack and push the next element of pushed array? If we continue this process and reach at the last of popped array, we can tell that the push and pop sequences are valid, right?

This way, we do not need to generate permutations of pushed and popped elements!

Let’s see how this will work in action. Below image is the initial state of our problem. We have taken an empty stack (named test_stack) to keep our pushed elements.

At the beginning, we will push the first element from pushed array. An index j will point to the first element of the popped array. After pushing the first element (from pushed), we will check if that element is the current element (pointed by j) of popped array or not. If it is, we will pop this element from our test_stack and move j forward. If not, we will continue pushing the next element to our test_stack.

(When we say push, we mean we push from pushed array to our test_stack)

Okay, so we pushed 1 to our stack and found that 1 is not the current element of popped.

In other words, popped[j] != test_stack.top(). So we will continue pushing.

Next, we will push 2 to stack.

Still, popped[j] != test_stack.top(). So we will continue pushing.

Next, we will push 3 to stack.

Still, popped[j] != test_stack.top(). So we will continue pushing.

Next, we will push 4 to stack.

Wait! Now, popped[j] == test_stack.top() (4 == 4)!

So, we will do two things now. We will pop 4 from our stack and move j forward and continue to check even after popping 4 from stack and moving j forward, if the current top element of our stack (3) is equal to the element pointed by j (5) or not. If not, we will start again to push the next element.

Now, we push the next element (5) to stack.

Now, again the top element of our stack is same as the current element of popped array. So, we will pop the top element from our stack and move j forward.

After moving j forward, it is pointing to 3 and the current top element of stack is also 3!

So, we pop it and move j forward.

After moving j forward, it is pointing to 2 and the current top element of stack is also 2!

So, we pop it and move j forward.

After moving j forward, it is pointing to 1 and the current top element of stack is also 1!

So, we pop it and move j forward.

At this point, j has finished its traversal to the entire popped array and j has now a value equal to the length of the popped array. This means, the pop sequence can be generated with the push sequence. In other words, the pushed and popped sequence is valid!

If you face difficulty understanding the explanation, please check the images again and think deep. If you still have difficulty, please write to us in the comment box which part was hard to fathom. We will reply you and will improve our explanation.

Code
C++
class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        
        stack<int> test_stack; // a temporary stack to check validity of push pop sequence
        int j = 0;
        
        for(int i = 0; i < pushed.size(); i++)
        {
            test_stack.push(pushed[i]);
            
            while(!test_stack.empty() && j < popped.size())
            {
                if(test_stack.top() != popped[j])
                    break;
                else{
                    test_stack.pop(); //top element of test_stack is the cuurent element which was popped
                                      //so, we pop from test_stack
                    j++;              //and we move to the next element in popped array
                }
            }
        }
        if(j == popped.size())
            return true;
        return false;
    }
};
Time and Space Complexity

We need to go through both the arrays ones. So, we have an O(N) time complexity.

We also need an extra stack to save pushed elements temporarily. Which means, we have an O(N) space complexity.

Here N is the length of pushed or popped array. Both has the same length, right?

Conclusion

This is a problem in a difficulty range of between Easy and Medium (our opinion). But still, we might not have done a good job explaining the solution. If you find hard time understanding, please write a note to us in the comment box. We will definitely try to improve and will reply you!

Till our next post, Happy coding! 😀

Bonus – System Design!

ByteByteGo is by far the best system design resource found on the internet. They are growing like crazy!

We suggest you checkout their course if you really want to dive deep in system design and want to have a better interview.

Here is the link: ByteByteGo!

Disclaimer: this is a genuine suggestion, but we have some benefits too! We get commission if you buy their course. However, there are other courses online which we do not promote. Because we promote only things that are the best in our opinion and those we really feel like helpful for our audience.

29 thoughts on “Validate Stack Sequences”

  1. I like this post, enjoyed this one thanks for putting up. “‘I have done my best.’ That is about all the philosophy of living one needs.” by Lin Yutang.

  2. Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

  3. Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you. 20bet

  4. Hi foolishhungry.com webmaster, Your posts are always well-supported by facts and figures.

  5. Hi there very nice website!! Guy .. Excellent .. Superb .. I will bookmark your web site and take the feeds additionally…I am happy to search out so many helpful info right here within the post, we’d like work out extra techniques in this regard, thanks for sharing.

  6. To the foolishhungry.com webmaster, Your posts are always well-supported and evidence-based.

  7. Hi, great post There is a problem with your website on Internet Explorer. Despite being the most popular browser, many people will not be able to view your excellent work because of this issue.

  8. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is excellent, let alone the content!

  9. This website is amazing. The excellent content demonstrates the creator’s passion. I’m in disbelief and hope to see more of this incredible content.

  10. Just wish to say your article is as astounding. The clarity in your post is just cool and i could suppose you are an expert in this subject. Well with your permission let me to take hold of your feed to keep updated with imminent post. Thanks one million and please keep up the rewarding work.

  11. Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do it Your writing style has been amazed me Thank you very nice article

  12. I’m typically to running a blog and i really respect your content. The article has actually peaks my interest. I’m going to bookmark your site and preserve checking for brand new information.

  13. Hey very cool blog!! Man .. Beautiful .. Amazing .. I will bookmark your site and take the feeds also厈I am happy to find so many useful info here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .

  14. I keep listening to the reports speak about getting boundless online grant applications so I have been looking around for the top site to get one. Could you advise me please, where could i get some?

  15. obviously like your website but you need to test the spelling on quite a few of your posts Several of them are rife with spelling problems and I to find it very troublesome to inform the reality on the other hand Ill certainly come back again

Leave a Reply

Your email address will not be published. Required fields are marked *