Queue using Two Stacks

Sort by

recency

|

239 Discussions

|

  • + 0 comments

    Thanks to hackerrank4021 , Java solution is below.

    import java.io.*;
    import java.util.*;
    
    /*
    a. For insert, insert into stack1.
    b. For deque, deque from stack2. If it is not empty transfer from 1 to 2 and deque from 2.
    c. For peek, show peek of stack2. If empty transfer from 1 to 2 and then peek from 2.
    */
    
    public class Solution {
    
        public static Stack<Integer> sta1 = new Stack();
        public static Stack<Integer> sta2 = new Stack();
        
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            
            // only below is poss in stacks
            // sta1.removeLast();
            Scanner sc = new Scanner(System.in);
            int noQ = sc.nextInt();
            
            while (noQ-- > 0) {
                switch (sc.next()) {
                    case "1":
                        insertQueue(sc.nextInt());
    
                        // print queue top
                        // printQueueHead();
            
                        break;
    
                    case "2":
                        deQueue();
                        break;
    
                    case "3":
                        printQueueHead();
                        break;
    
                    case "q":
                        return;
    
                    default:
                        System.out.println("Invalid input!");
                        break;
                }
            }
        }
        
        public static void insertQueue(int item) {
            sta1.add(item);
        }
        
        public static void transfer() {
            if(sta1.size() == 0)
                return;
            do {
                sta2.push(sta1.pop());
            }while(sta1.size() > 0);
        }
            
        public static Integer deQueue() {
    
            if(sta2.size() == 0) {
                if(sta1.size() == 0) {
                    return null;
                }
                transfer();
            }
            
            return sta2.pop();
        }
        
        // sta1 s last element is the queue head
        public static void printQueueHead(){
            
            if(sta2.size() == 0) {
                if(sta1.size() == 0) {
                    return;
                }
                transfer();
            }
            
            System.out.println(sta2.peek());
        }
    }
    
  • + 0 comments
    function processData(input) {
      // Define a queue
      class Fifo {
        constructor() {
          this.stackEnqueue = [];
          this.stackDequeue = [];
        }
    
        enqueue(x) {
          this.stackEnqueue.push(x);
        }
    
        transfer() {
          while (this.stackEnqueue.length > 0) {
            this.stackDequeue.push(this.stackEnqueue.pop());
          }
        }
        dequeue() {
          if (this.stackDequeue.length === 0) {
            this.transfer();
          }
          this.stackDequeue.pop();
        }
        peek() {
          if (this.stackDequeue.length === 0) {
            this.transfer();
          }
          if (this.stackDequeue.length === 0) {
            return null;
          } else {
            return this.stackDequeue[this.stackDequeue.length - 1];
          }
        }
      }
    
      let q = new Fifo();
    
      // Parse input
    
      const inputs = input.split('\n');
    
      for (let i = 1; i <= Number(inputs[0]); i++) {
        const element = inputs[i];
        const inputArray = element.split(' ');
    
        const action = Number(inputArray.shift());
        const value = Number(inputArray.join(''));
    
        switch (action) {
          case 1:
            q.enqueue(value);
            break;
    
          case 2:
            q.dequeue();
            break;
    
          case 3:
            console.log(q.peek());
            break;
    
          default:
            console.log('DEFAULT REACHED');
            console.log('Unexpected action', action, 'With Value', value);
    
            break;
        }
      }
    }
    
  • + 0 comments

    I am quite new to coding so I just used the knowledge on linked lists i gained from the previous exercise. This passed all the tests but could someone help me diagnose the complexity of my solution:

    # Enter your code here. Read input from STDIN. Print output to STDOUT
    class LinkedListNode():
        data: int = None
        next: 'LinkedListNode' = None
    
    
    class Queue():
        def __init__(self):
            self.head = None
            self.tail = None
    
        def enqueue(self, x):
            final_element = LinkedListNode()
            final_element.data = x
            # Handle empty queue case
            if not self.head:
                self.head = final_element
                if not self.tail:
                    self.tail = final_element
            else:
                self.tail.next = final_element
                self.tail = self.tail.next
    
        def dequeue(self):
            # Handle empty queue case
            if not self.head:
                return None
            dequeue_value = self.head.data
            self.head = self.head.next
            # If queue is empty, remove tail
            if self.head is None:
                self.tail = None
            return dequeue_value
    
        def handle_query(self, query):
            query_type = query[0]
            # Enqueue query
            if query_type == 1:
                x = query[1]
                self.enqueue(x)
            # Dequeue query
            elif query_type == 2:
                return self.dequeue()
            # Print query
            elif query_type == 3:
                if self.head.data:
                    print(self.head.data)
                else:
                    print(None)
    
    if __name__ == "__main__":
        q = int(input())
        queue = Queue()
        for _ in range(q):
            query = list(map(int, input().split()))
            queue.handle_query(query)
    
  • + 0 comments

    There is no Go template...

  • + 0 comments

    You could have two stacks: stack1 and stack2. You could then dequeue everything in stack1 into stack2 for operations 2 and 3, and then requeue them back into stack1 for further elements. This will not have a good time complexity.

    Consider: We enqueue elements into stack1:

    stack1 = [3,2,1] stack2=[] (empty)

    We get a dequeue/peek operation. We must unstack everything into stack2. Everything now looks like this:

    stack1 = [] stack2 = [1,2,3]

    We read/pop 1.

    Do we really need to put everything back into stack1?

    If we only unstack stack1 when stack2 is empty. We can keep adding new elements to stack1 without touching stack2. Any remaining elements in stack2 at this point are in the proper FIFO order as of when it was last updated. Anything added to stack1 at this point would need to wait for stack2's elements to be dequeued anyways.

    Consider:

    Enqueue 4: stack1 = [4] stack2 = [2,3]

    Because stack2 still has elements, if we get a peek/pop operation, we will next read/pop 2.

    You can think of your total structure like so: [stack2][stack1]: [2,3][x...4] where (x..). represents potential other elements put on stack1.