Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Problem statement: https://leetcode.com/problems/implement-queue-using-stacks/description/
- *
- * Notes: This implementation prioritizes efficiency for enqueuing (adding)
- * items from the queue, with a constant time complexity (O(1)).
- * Dequeuing (removing) or peeking an item from the queue has a linear time complexity (O(n)).
- *
- **/
- class Stack {
- constructor() {
- this.items = [];
- };
- push(item) {
- this.items.push(item);
- }
- pop() {
- return this.items.pop();
- }
- peek() {
- return this.items[this.items.length - 1];
- }
- isEmpty() {
- return !this.items.length
- }
- size() {
- return this.items.length();
- }
- }
- class MyQueue {
- constructor() {
- this.queueStack = new Stack();
- this.helperStack = new Stack();
- }
- push(item) {
- // EFFICIENT ENQUEUE
- this.queueStack.push(item);
- }
- pop() {
- // COSTLY DEQUEUE
- // move all items from queueStack to helperStack
- while(!this.queueStack.isEmpty()) {
- this.helperStack.push(this.queueStack.pop());
- }
- // deQueue item from top of helperStack
- const dequeuedItem = this.helperStack.pop();
- // move all items back to queueStack from helperStack
- while(!this.helperStack.isEmpty()) {
- this.queueStack.push(this.helperStack.pop());
- }
- return dequeuedItem;
- }
- peek() {
- // COSTLY PEEK
- while(!this.queueStack.isEmpty()) {
- this.helperStack.push(this.queueStack.pop());
- }
- const peekedItem = this.helperStack.peek();
- while(!this.helperStack.isEmpty()) {
- this.queueStack.push(this.helperStack.pop());
- }
- return peekedItem;
- }
- empty() {
- return this.queueStack.isEmpty();
- }
- };
- /**
- * Your MyQueue object will be instantiated and called as such:
- * var obj = new MyQueue()
- * obj.push(x)
- * var param_2 = obj.pop()
- * var param_3 = obj.peek()
- * var param_4 = obj.empty()
- */
Advertisement
Add Comment
Please, Sign In to add comment