Validate Stack Sequences in C++

C++Server Side ProgrammingProgramming

Suppose we have two sequences pushed and popped with distinct values, we have to find true if and only if this could have been the result of a sequence of the push and pop operations on an initially empty stack. So if the input is push = [1,2,3,4,5], and pop = [4,5,3,2,1], then the output will be true. We can use push(1), push(2), push(3), push(4), pop() : 4, push(5), pop() : 5, pop() : 3, pop() : 2, pop() : 1

To solve this, we will follow these steps −

  • Create one method called solve(). This will take pushed and popped arrays

  • define a stack st, set index := 0

  • for i in range 0 to size of pushed array

    • push pushed[i] into st

    • if popped[index] = stack top element, then

      • index := index + 1

      • pop from stack

      • while st is not empty, and popped[index] = top of st

        • index := index + 1

      • delete from st

  • while index < size of popped

    • if popped[index] = stack top, then

      • increase index by 1

      • delete from stack

    • otherwise come out from the loop

  • return true, when stack is empty

  • this solve method will be called from the main section like below −

  • return solve(pushed, popped)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool solve(vector<int>& pushed, vector<int>& popped){
      stack <int> st;
      int currentIndexOfPopped = 0;
      for(int i =0;i<pushed.size();i++){
         st.push(pushed[i]);
         if(popped[currentIndexOfPopped] == st.top()){
            currentIndexOfPopped++;
            st.pop();
            while(!st.empty() && popped[currentIndexOfPopped]==st.top()){
               currentIndexOfPopped++;
               st.pop();
            }
         }
      }
      while(currentIndexOfPopped <popped.size()){
         if (popped[currentIndexOfPopped]==st.top()){
            currentIndexOfPopped++;
            st.pop();
         }else{
            break;
         }
      }
      return st.empty();
   }
   bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
      Solution s;
      bool flag = s.solve(pushed, popped);
      return flag;
   }
};
main(){
   vector<int> v = {1,2,3,4,5};
   vector<int> v1 = {4,5,3,2,1};
   Solution ob;
   cout << (ob.validateStackSequences(v, v1));
}

Input

[1,2,3,4,5]
[4,5,3,2,1]

Output

1
raja
Published on 05-Mar-2020 05:48:04
Advertisements