How to use Array as Stack In Javascript
- 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)
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