Sollicitatievraag bij Microsoft

Implement a stack using two queues.

Antwoorden op sollicitatievragen

Anoniem

5 okt 2014

I think the answer the interview is looking for is something like this: You kept two queue's one of them is always empty. Push - Enqueue to the empty queue, and then sequentially dequeue everything on the other queue to this "empty" queue, complexity O(N) Pop - Dequeue the non-empty queue O(1) This solution is in favor of pop, it can be done in favor of push also.

3

Anoniem

5 okt 2014

To add on to the previous answer, both can be done in O(1) if a special element (end-of-queue) is allowed to be introduced. Push - push to the queue that has the end-of-queue element as the first element. Pop - Dequeue both queue, one of them is end-of-queue element, so serve the result of the other queue.

2

Anoniem

7 nov 2011

You only need 1 queue to implement a stack. queues are more powerful. If there are N elements in the queue and you need to pop the last element in order to simulate the stack LIFO behavior, just pop the first N-1 elements and immediately push them back into the queue. Then pop the Nth element and return it. Done. You are basically cycling through the queue to get the element you want without disrupting the rest of the elements. Note O(N) time for pop(). This is what valentino said above but you don't 2 queues, just 1, to accomplish it.

1

Anoniem

10 nov 2011

totally Agree with bob, you only need one queue, I guess using the 2 queues answer is based on the question "2 queues" but once again this can be solve with just one queue.

1

Anoniem

3 okt 2011

The question asks to implement a stack with 2 queues. Your solution has 2 stacks and is implementing a queue.

Anoniem

30 okt 2011

One the blog below, there is a detailed solution about how to implement a queue with two stacks: http://codercareer.blogspot.com/2011/10/no-17-queue-implemented-with-two-stacks.html It is quite similar to simulate a stack with two queues.

Anoniem

28 okt 2011

it is pretty similar, on Queue check which queue is not empty and enqueue in that one, if both are empty pick one. On Deque, start dequeue from the queue that is not empty and queue the element to the other queue until you reach the last element.