Python solution with detailed explanation


  • 0
    G

    Solution

    Implement Queue using Stacks https://leetcode.com/problems/implement-queue-using-stacks/?tab=Description

    • Use two stacks - one for enqueue and other for dequeue.
    • When we need to do pop or peek and st_dq is empty, then we push all elements from st_enq into st st_dq and pop or peek. But we do not push back all elements back - instead we keep the dq stack in the same position.
    class MyQueue(object):
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.st_enq, self.st_dq = [], []
            
        def push(self, x):
            """
            :type x: int
            :rtype: nothing
            """
            self.st_enq.append(x)
            
        def pop(self):
            """
            :rtype: nothing
            """
            if len(self.st_dq) == 0:
                while self.st_enq:
                    self.st_dq.append(self.st_enq.pop())
            return self.st_dq.pop()
            
        def peek(self):
            """
            :rtype: int
            """
            if len(self.st_dq) == 0:
                while self.st_enq:
                    self.st_dq.append(self.st_enq.pop())
            return self.st_dq[-1]
            
        def empty(self):
            """
            :rtype: bool
            """
            return len(self.st_enq) + len(self.st_dq) == 0
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.