Skip to content
Exercises · Q3

Q.Write a program to reverse a string using stack.

Yanam BieapTextbookSubjective· 3mImportance★★★★★
38% · 5/13 Questions
✓ Free question

Use a stack to reverse a string by pushing each character onto the stack, then popping them all to build the reversed string — the LIFO property does the reversal.

Why a Stack?

A stack is a Last-In-First-Out (LIFO) data structure. When you push characters of a string onto a stack in order and then pop them all, they come out in reverse order. This makes the stack the natural tool for string reversal: the first character pushed becomes the last one popped.

The algorithm is straightforward:

  1. Push each character of the original string onto the stack (left to right).
  2. Pop all characters from the stack and concatenate them into a new string.

Because the last character pushed is the first one popped, the result is the reversed string.


Implementation

We can implement this using Python's built-in list as a stack (with append() for push and pop() for pop), or we can write a simple Stack class for clarity.

Approach 1: Using a List as a Stack

def reverse_string(s):
    stack = []
    
    # Push all characters onto the stack
    for char in s:
        stack.append(char)
    
    # Pop all characters to build the reversed string
    reversed_str = ""
    while stack:
        reversed_str += stack.pop()
    
    return reversed_str

# Test
original = "HELLO"
reversed_result = reverse_string(original)
print(f"Original: {original}")
print(f"Reversed: {reversed_result}")

Output:

Original: HELLO
Reversed: OLLEH

Key lines:

  • stack.append(char) pushes each character onto the stack in the order they appear.
  • stack.pop() removes and returns the top element (the last character pushed), so concatenating these gives the reverse.

Approach 2: Using a Custom Stack Class

For a more structured solution that explicitly shows stack operations:

class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        return None
    
    def is_empty(self):
        return len(self.items) == 0

def reverse_string(s):
    stack = Stack()
    
    # Push all characters
    for char in s:
        stack.push(char)
    
    # Pop all characters
    reversed_str = ""
    while not stack.is_empty():
        reversed_str += stack.pop()
    
    return reversed_str

# Test
original = "PYTHON"
reversed_result = reverse_string(original)
print(f"Original: {original}")
print(f"Reversed: {reversed_result}")

Output:

Original: PYTHON
Reversed: NOHTYP

The Stack class encapsulates the stack behavior. The is_empty() check ensures we stop popping when the stack is exhausted.


Step-by-Step Trace

For the string "ABC":

StepOperationStack (bottom → top)Reversed String
1Push 'A'['A']""
2Push 'B'['A', 'B']""
3Push 'C'['A', 'B', 'C']""
4Pop → 'C'['A', 'B']"C"
5Pop → 'B'['A']"CB"
6Pop → 'A'[]"CBA"

The final reversed string is "CBA".


Tip

Python strings are immutable, so repeatedly concatenating with += inside a loop can be slow for very long strings. For better performance, collect popped characters in a list and join them at the end:

chars = []
while not stack.is_empty():
    chars.append(stack.pop())
reversed_str = "".join(chars)
✓Final answer

The program pushes each character of the input string onto a stack, then pops them all to construct the reversed string. For "HELLO", the output is "OLLEH".

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.