| title | difficulty | tags | ||
|---|---|---|---|---|
Reverse a String Using Stack |
🟢 Easy |
|
Given a string, write a function that uses a stack to reverse the string. Return the reversed string.
Example 1:
Input: "Hello, World!"
Output: "!dlroW ,olleH"
Example 2:
Input: "OpenAI"
Output: "IAnepO"
Example 3:
Input: "Stacks are fun!"
Output: "!nuf era skcatS"
1 <= s.length <= 10⁵s[i]is a printable ASCII character
A stack reverses order naturally: first in, last out. Push all characters onto the stack, then pop them off to build the reversed string.
- Push all characters onto the stack
- Pop each character and append to result
- Join and return
-
Time Complexity:
$O(n)$ — push and pop each character once -
Space Complexity:
$O(n)$ — stack holds all characters
class Solution:
def reverseString(self, s: str) -> str:
stack = list(s) # push all characters
reversed_list = []
while stack:
reversed_list.append(stack.pop()) # LIFO: last char comes out first
return ''.join(reversed_list)