Reverse a String using Stack
Pattern: Implementation
Push every character onto a stack, then pop them all. A stack gives items back newest first, so the characters come out in reverse order.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a string, return it reversed, using a stack. "GeeksforGeeks" gives "skeeGrofskeeG".
The catalogue has no practice link for this one.
Think first
- In what order does a stack return items?
- What do you push, and when do you pop?
Hints
Brute force, and why it fails
Two pointers swapping from both ends also reverse in O(n) with O(1) extra space; the stack version shows the LIFO idea.
The key insight
Reversal is exactly what a stack does to a sequence.
Dry run
a0
b1
c2
s = "abc". Push a, b, c; c is on top.
Step 1 of 2
The plan
stack = []
for c in s: push c
out = ""
while stack: out += pop
Complexity
- Time
O(n)- Space
O(n)
Each character is pushed and popped once, and the stack holds all of them.
Edge cases
- One character.
- A palindrome comes back unchanged.
- Spaces are characters too.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public String reverseString(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) stack.push(c); // the last character pushed is on top
StringBuilder out = new StringBuilder();
while (!stack.isEmpty()) out.append(stack.pop()); // pops come out last-in, first-out
return out.toString();
}
}C++
class Solution {
public:
string reverseString(string s) {
stack<char> st;
for (char c : s) st.push(c); // the last character pushed is on top
string out;
while (!st.empty()) { out += st.top(); st.pop(); } // pops come out last-in, first-out
return out;
}
};Python
class Solution:
def reverseString(self, s: str) -> str:
stack = []
for c in s:
stack.append(c) # the last character pushed is on top
out = []
while stack:
out.append(stack.pop()) # pops come out last-in, first-out
return "".join(out)Common mistakes
- Building the result with repeated string concatenation in Java (use a
StringBuilder). - Popping while also pushing in the same loop.