Problem Statement
Use a stack to reverse a string. This technique leverages the Last In, First Out (LIFO) nature of stacks to retrieve characters in reverse order.
Example Usage
Additional Examples:
- Input:
"world"
- Input:
"javascript"
JavaScript Stack - Using Custom Stack Class
We’ll use the following custom Stack
class to reverse the string. This class includes methods like push
, pop
, peek
, isEmpty
, size
, and clear
.
Dry Run
For the input "hello"
:
- Push each character onto the stack:
- Push
h
→ Stack: [h]
- Push
e
→ Stack: [h, e]
- Push
l
→ Stack: [h, e, l]
- Push
l
→ Stack: [h, e, l, l]
- Push
o
→ Stack: [h, e, l, l, o]
- Pop each character from the stack and build reversed string:
- Pop
o
→ reversed = "o"
- Pop
l
→ reversed = "ol"
- Pop
l
→ reversed = "oll"
- Pop
e
→ reversed = "olle"
- Pop
h
→ reversed = "olleh"
The final output is "olleh"
.
Complexity Analysis
Custom Defined Stack Methods
- Time Complexity:
push
and pop
operations are both O(1). Therefore, reversing a string of length n
with n
push
and pop
operations is O(n).
- Space Complexity: O(n) for storing characters in the stack.
Conclusion
Using a stack to reverse a string is an efficient way to leverage the LIFO property. This approach provides a clean solution for reversing strings, making it a great example of applying the stack data structure.