leetcode 232. Implement Queue using Stacks (Python)

08 Jun 2020 Leetcode Stack

232. Implement Queue using Stacks (Python)

Stack.

Description

Implement the following operations of a queue using stacks.

  • push(x) – Push element x to the back of queue.
  • pop() – Removes the element from in front of queue.
  • peek() – Get the front element.
  • empty() – Return whether the queue is empty.

Note

Do not modify the linked list.

Sample I/O

Example 1

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

Notes:

  • You must use only standard operations of a stack – which means only push to top, top/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty queue).

Methodology

To implement queue by using stack, the push and empty will be exactly same as stack. For pop and top operations, we need to reorder the number in stack. However, since the operations are dynamic changing, to save the cost, the best way is to create extra space called pop_stack to append number that pop out from original stack, this will reverse order will minimum cost.

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.push_stack = []
        self.pop_stack = []

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.push_stack.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if self.empty(): return
        if len(self.pop_stack):
            return self.pop_stack.pop()
        else:
            while len(self.push_stack):
                self.pop_stack.append(self.push_stack.pop())
        return self.pop_stack.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        if self.empty(): return
        if len(self.pop_stack):
            return self.pop_stack[-1]
        else:
            while len(self.push_stack):
                self.pop_stack.append(self.push_stack.pop())
        return self.pop_stack[-1]

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return len(self.push_stack)==False and len(self.pop_stack) == False

BigO

No need to iterate the stack or list for append and is empty but we do need to iterate the stack or list for pop and top operations. This will cost O(n)

Search

    Table of Contents