Interview Questions

  • View all interview questions
  • blank
  • Implement a queue using two stacks
    In another interview question we explained what a queue is and how to implement one using a linked list. Now we'll provide a solution to a common interview question, which is how to implement a queue using two stacks. A stack is a data structure where items can be added to a collection and removed from it just like in a queue, except the difference is the order in which they are removed. In a stack, the last item added will be the first item removed (last in, first out). Stacks usually have two basic methods, push, which adds an item into the stack, and pop, which "pops off" the top item from the stack. You can think of a stack like a physical stack of books: to add a new book to the stack you simply place the book on top, and then when you want to make the stack smaller you start removing books from the top of the stack.

    Example of stack operations

    Algorithm for queue using two stacks

    For example: Suppose we push "a", "b, "c" to a stack. If we are trying to implement a queue and we call the dequeue method 3 times, we actually want the elements to come out in the order: "a", "b, "c", which is in the opposite order they would come out if we popped from the stack. So, basically, we need to access the elements in the reverse order that they exist in the stack. The following algorithm will implement a queue using two stacks. (1) When calling the enqueue method, simply push the elements into the stack 1. (2) If the dequeue method is called, push all the elements from stack 1 into stack 2, which reverses the order of the elements. Now pop from stack 2.

    Code

    // implement stacks using plain arrays with push and pop functions
    var Stack1 = [];
    var Stack2 = [];
    
    // implement enqueue method by using only stacks
    // and the push and pop functions
    function Enqueue(element) {
      Stack1.push(element);
    }
    
    // implement dequeue method by pushing all elements
    // from stack 1 into stack 2, which reverses the order
    // and then popping from stack 2
    function Dequeue() {
      if (Stack2.length === 0) {
        if (Stack1.length === 0) { return 'Cannot dequeue because queue is empty'; }
        while (Stack1.length > 0) {
          var p = Stack1.pop();
          Stack2.push(p);
        }
      }
      return Stack2.pop();
    }
    
    Enqueue('a');
    Enqueue('b');
    Enqueue('c');
    Dequeue(); 
    
    # implement stacks using plain lists with push and pop functions
    Stack1 = []
    Stack2 = []
    
    # implement enqueue method by using only stacks
    # and the append and pop functions
    def Enqueue(element):
      Stack1.append(element)
      
    # implement dequeue method by pushing all elements
    # from stack 1 into stack 2, which reverses the order
    # and then popping from stack 2
    def Dequeue():
      if len(Stack2) == 0:
        if len(Stack1) == 0:
          return 'Cannot dequeue because queue is empty'
        while len(Stack1) > 0:
          p = Stack1.pop()
          Stack2.append(p)
      return Stack2.pop()
    
    Enqueue('a')
    Enqueue('b')
    Enqueue('c')
    print Dequeue()
    
    Run Code
    Run Code

    Running time

    The worst case running time for implementing these operations using stacks is O(n) because you need to transfer n elements from stack 1 to stack 2 when a dequeue method is called. Pushing to stack 1 is simply O(1).

    Sources

    https://www.glassdoor.com/Interview/How-to-implement-a-queue-simply-using-two-stacks-and-how-to-implement-a-highly-efficient... http://www.careercup.com/question?id=4399683
    mrdaniel published this on 11/24/15 | linked list, queue, stack, Google, Facebook
    Comments
    Login to submit a comment