Daily LeetCoding Challenge for May, Day 5.

Problem was to implement stack using two queue.
We need to perform basic operations like push,pop,top,empty.
Primary queue was q1.

for push(),empty() and top() I used only one queue(q1)

push()

  • whenever a new item was pushed, it was added to q1.
void push(int x) {
        q1.push(x);
    }

empty()

  • For empty I just check it q1 was empty or not.
bool empty() {
        return q1.empty();
    }

top()

  • return q1.back()
int top() {
        return q1.back();     
    }

pop()

  • I created one more queue and moved everything from q1 to q2 leaving the last element.
  • then I stored the last element in a variable x, deleted it from q1.
  • now q1 is empty and q2 has all remaining elements.
  • then I simply copied back everything from q2 to q1.
  • return x.
int pop() {
        queue<int> q2;                      //creating q1
        int  x;
        while(q1.size()!=1){                // moved everything from q1 to q2 leaving the last element.
             x=q1.front();
            q1.pop();
            q2.push(x);
        }
         x=q1.front();                      //storing and deleting last element from q1
        q1.pop();
        q1=q2;                              //coping everything from q2 to q1
        return x;                            //returning x
    }

image

LInk to my code

Time complexity:

  • push- O(n)
  • top- O(1)
  • empty- O(1)
  • pop- O(n) and space complexity - O(n)

I hope you will find my solution helpful!😊

Comments (0)