Leetcode 983 Solution

This article provides solution to leetcode question 983 (validate-stack-sequences)

https://leetcode.com/problems/validate-stack-sequences

Solution

class Solution(object):
    def validateStackSequences(self, pushed, popped):
        """
        :type pushed: List[int]
        :type popped: List[int]
        :rtype: bool
        """
        i = 0
        j = 0
        s = []

        while i < len(pushed) or j < len(popped):
            stuck = True

            while s and popped[j] == s[-1]:
                s.pop(-1)
                j += 1
                stuck = False

            if i < len(pushed):
                s.append(pushed[i])
                i += 1
                stuck = False

            if stuck:
                return False

        return True