Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Validate parenthesesE02. Reverse a string using a stackE03. Implement a stack with push, pop, and peekE

Problem No 2

Reverse a string using a stack

Easy

8 minute session

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'.

Code editor
Loading editor…

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.

03:42 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.