micahbales

232. Implement Queue using Stacks (COSTLY DEQUEUE)

Oct 13th, 2023
936
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * Problem statement: https://leetcode.com/problems/implement-queue-using-stacks/description/
  3. *
  4. * Notes: This implementation prioritizes efficiency for enqueuing (adding)
  5. * items from the queue, with a constant time complexity (O(1)).
  6. * Dequeuing (removing) or peeking an item from the queue has a linear time complexity (O(n)).
  7. *
  8. **/
  9.  
  10. class Stack {
  11.     constructor() {
  12.         this.items = [];
  13.     };
  14.  
  15.     push(item) {
  16.         this.items.push(item);
  17.     }
  18.  
  19.     pop() {
  20.         return this.items.pop();
  21.     }
  22.  
  23.     peek() {
  24.         return this.items[this.items.length - 1];
  25.     }
  26.  
  27.     isEmpty() {
  28.         return !this.items.length
  29.     }
  30.  
  31.     size() {
  32.         return this.items.length();
  33.     }
  34. }
  35.  
  36.  
  37.  
  38. class MyQueue {
  39.     constructor() {
  40.         this.queueStack = new Stack();
  41.         this.helperStack = new Stack();
  42.     }
  43.  
  44.     push(item) {
  45.         // EFFICIENT ENQUEUE
  46.         this.queueStack.push(item);
  47.     }
  48.    
  49.     pop() {
  50.         // COSTLY DEQUEUE
  51.  
  52.         // move all items from queueStack to helperStack
  53.         while(!this.queueStack.isEmpty()) {
  54.             this.helperStack.push(this.queueStack.pop());
  55.         }
  56.        
  57.         // deQueue item from top of helperStack
  58.         const dequeuedItem = this.helperStack.pop();
  59.  
  60.         // move all items back to queueStack from helperStack
  61.         while(!this.helperStack.isEmpty()) {
  62.             this.queueStack.push(this.helperStack.pop());
  63.         }
  64.  
  65.         return dequeuedItem;
  66.     }
  67.  
  68.     peek() {
  69.         // COSTLY PEEK
  70.         while(!this.queueStack.isEmpty()) {
  71.             this.helperStack.push(this.queueStack.pop());
  72.         }
  73.  
  74.         const peekedItem = this.helperStack.peek();
  75.        
  76.         while(!this.helperStack.isEmpty()) {
  77.             this.queueStack.push(this.helperStack.pop());
  78.         }
  79.  
  80.         return peekedItem;
  81.     }
  82.  
  83.     empty() {
  84.         return this.queueStack.isEmpty();
  85.     }
  86. };
  87.  
  88. /**
  89.  * Your MyQueue object will be instantiated and called as such:
  90.  * var obj = new MyQueue()
  91.  * obj.push(x)
  92.  * var param_2 = obj.pop()
  93.  * var param_3 = obj.peek()
  94.  * var param_4 = obj.empty()
  95.  */
Advertisement
Add Comment
Please, Sign In to add comment