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.
Approach
- Initialize a Stack: We create an instance of the
Stack class.
- Push Characters to Stack: For each character in the string, use the
push method to add it to the stack.
- Pop Characters from Stack: Pop each character from the stack and append it to a result string. Since the stack is LIFO, characters come out in reverse order.
- Return the Result: The final reversed string is returned.
Steps
- Create an instance of the
Stack class.
- Loop through each character of the input string, pushing each character onto the stack.
- Pop each character from the stack and concatenate to form the reversed string.
- Return the reversed string.
Time & Space Complexity
- Time Complexity:
push and pop operations are O(1), and since each character is pushed and popped once, the overall complexity is O(n), where n is the length of the string.
- Space Complexity: O(n), due to storing characters in the stack.
Code Snippet
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.