Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

946. Validate Stack Sequences 🌟🌟

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.

Greedy Intuitive

Code

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