WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Stack and Queue Problems · question 59 of 120

Can you reverse a stack without using any additional data structures?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

While there are numerous ways to solve this problem, given the constraint you’ve outlined — not using any additional data structures — we should solve it using recursion. The reason for this is because, even though it may not be entirely obvious at first, recursion has a built-in stack!

Here’s the general pseudocode:

1. Use the technique of removing all items from the stack recursively until it is empty.

2. While popping items off the stack in this recursive process, instead of immediately reinserting an item after removing it, delay this step until the stack is fully empty.

3. Then, insert all items back into it. The last item we pop off will be the first one we push back in, and so forth, effectively reversing the stack.

If you think about it long enough, this is akin to using an additional stack, but formally speaking, it’s completely void of any additional data structures.

Here’s the actual code for this process, in Python:

def insert_at_bottom(stack, item):
    if len(stack) == 0:
        stack.append(item)
    else:
        temp = stack.pop()
        insert_at_bottom(stack, item)
        stack.append(temp)


def reverse_stack(stack):
    if len(stack) > 0:
        temp = stack.pop()
        reverse_stack(stack)
        insert_at_bottom(stack, temp)

You first define a helper function, ‘insert_at_bottom‘, to place an item at the bottom of the stack. You then define your main function, ‘reverse_stack‘, which uses this helper to reverse the stack.

The function ‘reverse_stack‘ pops an item from the stack and calls itself to reverse the remaining items. Once that is achieved (the remaining stack is empty), it uses ‘insert_at_bottom‘ to place the popped items back but at the bottom of the stack. This results in the stack being reversed.

However, It’s important to note that this method might not be the most efficient one for large data sets and could potentially cause a stack overflow error due to high recursion depth especially in languages that have small maximum recursion depth like Python.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics