stack : gfg and other selected Ques Level Wise

                                 design and implementation





                                          Basic/Easy Level

Check for Balanced Brackets in an expression (well-formedness) using Stack:

Example

Input: exp = “[()]{}{[()()]()}” 
Output: Balanced

Input: exp = “[(])” 
Output: Not Balanced 

  bool ispar(string s)
    {
        stack<char> st;
        
        for(auto x:s){
            // push  when open bracket
            if(x=='(' || x=='{' || x=='['){
                st.push(x);
                continue;
            }
            // most imp
            //if stack is empty, then  x not be closing bracket
            // mtlb jo hm closinng push krne ja rhe hai, uska opening stack me phle se hona chaiye
            if(st.empty()) return false;
            
            //pop when closing bracket and its opening matching with top of stack
            if(x==')' && st.top()=='(') st.pop();
            else if(x=='}' && st.top()=='{') st.pop();
            else if(x==']' && st.top()=='[') st.pop();
            else return false;
        }
        //in last, if stack becomes empty then balanced otherwise not
        if(st.empty()) return true;
        return false;
    }




----


                                                Medium Level

Next Greater Element

For the input array [4, 5, 2, 25],'
Element       NGE
   4      -->   5
   5      -->   25
   2      -->   25
   25     -->   -1  https://www.geeksforgeeks.org/next-greater-element/


 vector<long long> nextLargerElement(vector<long long> arr, int n){
   
        unordered_map<long long,long long>mp;
        
        stack<long long> st;
        //reverse iterate
          for(int i=n-1;i>=0;i--){
            
            while(true){
                if(st.empty() || st.top()>arr[i]) break;
                st.pop();
            }
          
          mp[arr[i]]=st.empty()?-1:st.top();
          st.push(arr[i]);
        }
        vector<long long> v;
        
        for(auto x:arr) v.push_back(mp[x]);
     return v;
    }





---------------

Comments

Popular posts from this blog

c++ oops

Takeoff (hackerearth.3, datastructure, array 1-D)

Aptitude tricks