Validate Stack Sequences | February Leetcoding challenge 2021 | Day 26
logo
Manas Sinha
Developer | Designer

By Manas | 26 February 2021

February LeetCoding Challenge 2021

Day 26

Validate Stack Sequences

PROBLEM  STATEMENT:
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
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
strong>Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
  • 0 <= pushed.length == popped.length <= 1000
  • 0 <= pushed[i], popped[i] < 1000
  • pushed is a permutation of popped.
  • pushed and popped have distinct values.

Explanation

The simplest way to do it is to just have a stack and see if the given operations are feasible.We traverse through the pushed array and also we have a pointer i that moves over the popped array. If the stack is empty or the top element of the stack is not equal to popped[i] we push elements from pushed array to the stack. Else we pop the element from the stack and increment i until the stack is empty or the top element is not equal to popped[i]. At the end if stack is empty that means the given operations are feasible.
ALGORITHM:
  • Maintain a stack.
  • Traverse the pushed array from left to right and have a variable i initialised to zero.
  • Push the current element to the stack.
  • While stack is not empty and st.top() == popped[i], pop the top element of stack and increment i.
  • After traversing the entire pushed array return true if the stack is empty else return false.
  • Time complexity : O(n)
  • Space complexity : O(n)

code

C++

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int> st;
        
        int j=0;
        for(int i=0;i<pushed.size();++i){
              st.push(pushed[i]);
               while(!st.empty() && st.top() == popped[j]){
                    st.pop();
                    ++j;
                }            
        }
        return st.empty();
    }
};

PYTHON

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

LEAVE A COMMENT

If you like the post leave a comment and share it.

Leave a Reply