JavaScript Program to Reverse a String using Stack
Stack is the LIFO Data Structure that allows reversing a string by pushing characters onto the stack and popping them in reverse order to reconstruct the string.
Below are the approaches to reversing a String using Stack.
Table of Content
- Using Array as Stack
- Using Custom Stack Implementation
Using Array as Stack
- In this approach, we are using an array as a stack to reverse a string.
- We iterate through the characters of the string, pushing each character onto the stack.
- Then, we pop characters from the stack one by one to construct the reversed string, appending each popped character to the result variable until the stack is empty.
Example: The below example uses Array as a Stack to Reverse a String in JavaScript.
let str = "Hello, GFG!";
let stack = [];
let res = "";
for (let i = 0; i < str.length; i++) {
stack.push(str[i]);
}
while (stack.length > 0) {
res += stack.pop();
}
console.log(res);
Output
!GFG ,olleH
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n)
Using Custom Stack Implementation
- In this approach, we are using a custom stack implementation using a class.
- We define methods like push, pop, and isEmpty to manipulate the stack.
- We iterate through the characters of the string, pushing each character onto the stack using the custom push method.
- Then, we pop characters from the stack one by one using pop until the stack is empty, constructing the reversed string by appending each popped character to the result variable.
Example: The below example uses Custom Stack Implementation to Reverse a String in JavaScript.
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.items.length === 0) {
return "Underflow";
}
return this.items.pop();
}
isEmpty() {
return this.items.length === 0;
}
}
let str = "Hello, GFG!";
let stack = new Stack();
let res = "";
for (let i = 0; i < str.length; i++) {
stack.push(str[i]);
}
while (!stack.isEmpty()) {
res += stack.pop();
}
console.log(res);
Output
!GFG ,olleH
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n)