JB TAK FODEGA NHI .... TB TK CHODEGA NHI .... (MAANG)

SQP3 Implementation Stack Using Queue

In this Problem Implementation Stack Using Queue we Implemrnt using Singh Stack abd Double Stack

  • We Know that the stack works Top to Down Approch
  • We Know that the Queue works Down to Top Approch

  • Using 2 Queue

    Thougt Process

    In Order to Implement the Stack using Queue we Required 2 Queue

    push(x)
  • Add x to the Queue2
  • Put all the Element into the Queue1 -> Queue2
  • Swap Queue2 to Queue1

  • pop()
  • Remove the Top Element by Queue1
  • this is the Process Follow again and again


    Notes

    Note: Zoom for Better Understanding



    Code Zone!

    Python Code
    C++ Code
    Java Code
    Sb Mai He Kru ...

    Khud Bhi Kr le Khuch ..... Nalayk


    Time Complexity:O(N) Becouse all operation takes Time in Worst Case
    Space Complexity:O(N)+O(N) Becouse we used a 2 Queue that's why.


    But Interviewer Not happy this Solution Becouse we used 2 Queue Not Time To Optimized the Approch

    Using 1 Queue

    Intuition: As we know stack follows last in first out, which means we get the most recently inserted element whenever we remove an element from the stack. But queue follows first in first out, it means we get that element which we inserted in the starting at each deletion, it means if we want to use the queue like a stack we have to arrange elements in the queue such that we get the most recent element at each


  • Take a single queue.
  • push(x): Push the element in the queue.
  • Use a for loop of size()-1, remove element from queue and again push back to the queue, hence the most recent element becomes the most former element and vice versa.
  • pop(): remove the element from the queue.
  • top(): show the element at the top of the queue.
  • size(): size of the current queue.



  • Code Zone!

    Optimized Python Code
    Optimized C++ Code
    Optimized Java Code
    Sb Mai He Kru ...

    Khud Bhi Kr le Khuch ..... Nalayk


    Time Complexity:O(N) Becouse all operation takes Time in Worst Case
    Space Complexity:O(N)Becouse we used a 1 Queue that's why.


    Color
    Background
    Interview Docs File "All the Best" Team @DSAwithPrinceSingh

    ~ It's All About Consistency📈 Dedication🎯 HardWork💪 Happy Coding❤️ ~