Skip to content

Instantly share code, notes, and snippets.

@folksilva
Last active February 28, 2022 13:39
Show Gist options
  • Save folksilva/37a550af1a62885520f2f8a4357ff20d to your computer and use it in GitHub Desktop.
Save folksilva/37a550af1a62885520f2f8a4357ff20d to your computer and use it in GitHub Desktop.
Daily Coding Problem: Problem #1
"""
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].
Hint: Try working backwords from the end state.
https://dailycodingproblem.com/
"""
def queue_interleave(stack):
queue = []
while len(stack) > 0:
queue.append(stack.pop(0))
if len(stack) > 0:
queue.append(stack.pop())
return queue
if __name__ == '__main__':
# Read input, numbers separated by commas
stack = [int(n) for n in input().split(',')]
print(queue_interleave(stack))
@Nabushan
Copy link

Instead why can't we just create classes for both Stack and Queue along with its FILO and FIFO properties with a few of the necessary properties like "push()" and "pop()" for Stack and "enqueue()" and "dequeue()" for Queue. And the a few helper classes to do the above program in place(Consisting of Stack and Queue only as per the question).

https://github.com/Nabushan/Interleave_Stack_using_Queue/blob/d1f8c4bdbc73846bcae976f773ee894ebc2b93ef/code.py#L11

Hope so it helps if there's any changes, correction or Suggestion feel free to Comment.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment