Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Good morning. Here's your coding interview problem for today.
- This problem was asked by Google.
- Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue. This should be done in-place.
- Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue.
- For example, if the stack is [1, 2, 3, 4, 5], it should become [1, 5, 2, 4, 3]. If the stack is [1, 2, 3, 4], it should become [1, 4, 2, 3].
- */
- var stack = [1, 2, 3, 'a', 'b', 'c'];
- var queue = [];
- for(var i = 0; i < (stack.length / 2); i++) {
- var rightIndex = (stack.length - i) -1;
- queue.push(stack[i]);
- if (i !== rightIndex) {
- queue.push(stack[rightIndex]);
- }
- }
- // [1, 'c', 2, 'b', 3, 'a']
Add Comment
Please, Sign In to add comment