From 2657eb6a80cc9564cbe05124b3bc5c57f5045dd3 Mon Sep 17 00:00:00 2001 From: anebz Date: Mon, 23 Sep 2019 12:49:14 +0200 Subject: [PATCH] 3.4. queue via stack --- 03. Stacks and queues/3.4. queue_via_stack.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 03. Stacks and queues/3.4. queue_via_stack.md diff --git a/03. Stacks and queues/3.4. queue_via_stack.md b/03. Stacks and queues/3.4. queue_via_stack.md new file mode 100644 index 0000000..cef1b44 --- /dev/null +++ b/03. Stacks and queues/3.4. queue_via_stack.md @@ -0,0 +1,25 @@ +# 3.4. Queue via stacks + +> Implement a MyQueue class which implements a queue using two stacks + +## First idea + +A stack is LIFO, first element to get out is the one inserted last. And queue is FIFO. + +## Hints + +* How to remove the oldest item from a stack if you only have access to the newest item? + * Delete the one opposite in the array, so the last one... + * The trick must be inverting something because I need two stacks... +* We can remove the oldest elem in a stack by repeatedly removing the newest item (inserting those in the temporary stack, stack \#2) until we get down to one element, then put all the elems back. This requires O(n). Can we optimize for scenarios where we might do several pops in a row? + * If we could check if an elem is present in stack \#2 yes, but there's no such function + +## Solution + +We need to modify `peek` and `pop` to work in reverse order. We can use stack \#2 to reverse the order of the elements by popping s1 and pushing the elements on to s2. In each `peek` and `pop` operation, we pop everything from s1 onto s2, perform `peek` and `pop` and then push everything back. + +If two `peek`/`pop` must be performed, we need to move everything again. In a lazy approach, all elemenst remain in s2 until they must absolutely be reversed. + +stack_newest has the newest elements on top and stack_oldest has the oldest elements on top. When we dequeue an element, we dequeue from stack_oldest. If empty, transfer all elemens from stack_newest into stack_oldest in reverse order. + +[Code in Github](https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2003.%20Stacks%20and%20Queues/Q3_04_Queue_via_Stacks/MyQueue.java)