Lesson guide
What this Python exercise practices
Reverse a string using a stack is a beginner practice lesson that focuses on strings, formatting, traversal. It is designed to be solved in about 8 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- String values
- Basic indexing
Difficulty and time
- Level
- Beginner
- Estimated time
- 8 minutes
Practice path
Related public exercises
Summary
Reverse the characters of a string by simulating a stack.
Problem statement
Given an input string s, return a new string that is the reverse of s. Implement the reversal by using a stack (i.e., push all characters onto a stack and then pop them to build the reversed string). Avoid using Python slicing like s[::-1] to ensure the stack logic is used.
Task
Use a stack (LIFO) approach to reverse and return the input string.
Examples
Reverse 'hello'
Input
reverse_with_stack('hello')
Output
'olleh'
Explanation
Characters pushed then popped produce the reversed string.
Input format
A single string s. Example: 'hello'
Output format
Return the reversed string.
Constraints
0 <= len(s) <= 10^5. Aim for O(n) time and O(n) extra space for the stack.
Samples
Sample input 0
reverse_with_stack('abc')
Sample output 0
'cba'
Explanation 0
Reverses characters 'a','b','c' to 'cba'.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.