Validate Stack Sequences

Validate Stack Sequences

Leetcode Daily Challenge (13th April, 2023)

Problem Statement:-

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.

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

Problem Explanation with examples:-

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.

Intuition:-

  • If all the elements follow a stack push and pop order then the stack will be empty at the end.

  • So, we can have a pointer to the popped array and iterate over the pushed array.

  • If the top element of the stack is equal to the element pointed by the popped pointer then pop the element and increment the popped pointer.

  • If the stack is empty at the end then return True else return False.

Solution:-

  • Create a stack and a pointer to the popped array.

  • Iterate over the pushed array.

  • Push the element into the stack.

  • While the stack is not empty and the top element of the stack is equal to the element pointed by the popped pointer then pop the element and increment the popped pointer.

  • If the stack is empty at the end then return True else return False.

Code:-

JAVA Solution

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> st = new Stack<>();
        int popc = 0;
        int pushc = 0;
        for(int x: pushed){
            st.push(x);
            while(!st.empty() && st.peek() == popped[popc]){
                st.pop();
                popc++;
            }
        }


        return st.empty();
    }
}

Python Solution

class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        popc = 0
        st = []
        for i in pushed:
            st.append(i)
            while st and st[-1]==popped[popc]:
                st.pop()
                popc += 1

        return len(st) == 0

Complexity Analysis:-

TIME:-

The time complexity is O(n) where n is the length of the pushed array as we are iterating over the pushed array once.

SPACE:-

The space complexity is O(n) where n is the length of the pushed array as we are using a stack to store the pushed elements.

References:-

Connect with me:-

Did you find this article valuable?

Support Leeting-LCS by becoming a sponsor. Any amount is appreciated!