Similar Problems

Similar Problems not available

Validate Stack Sequences - Leetcode Solution

Companies:

LeetCode:  Validate Stack Sequences Leetcode Solution

Difficulty: Medium

Topics: stack array simulation  

The Validate Stack Sequences problem on LeetCode asks us to determine if a given sequence of push and pop operations on a given stack is valid. In other words, we need to check if after all the operations, the stack is empty.

To solve this problem, we can use a stack and simulate the given sequence of operations on it. For each operation in the input sequences, we check if it is a push or pop operation and perform the corresponding action on the stack.

If it is a push operation, we simply push the element to the top of the stack. If it is a pop operation, we check if the top of the stack contains the element to be popped. If it does, we pop the top element of the stack. If it doesn't, the sequence is invalid.

At the end, we check if the stack is empty. If it is, the sequence is valid, otherwise it is invalid.

Here is the detailed solution in Python:

def validateStackSequences(push: List[int], pop: List[int]) -> bool:
    stack = []
    i = 0   # Index for push sequence
    
    for x in pop:
        while not stack or stack[-1] != x:
            # Push elements from push sequence to stack
            # until the top of the stack is the element to be popped
            if i >= len(push):
                # We have exhausted all the elements in push
                return False
            stack.append(push[i])
            i += 1
        
        # At this point, the top of the stack is the element to be popped.
        # Pop it and move on to the next element in the pop sequence.
        stack.pop()
    
    # Check if the stack is empty at the end
    return not stack

The time complexity of this solution is O(N), where N is the total number of elements in the input sequences. This is because we need to perform at most N operations (push or pop) on the stack, each of which takes constant time. The space complexity is also O(N) because we are using a stack to simulate the sequence of operations.

Validate Stack Sequences Solution Code

1