Grokking Data Structures & Algorithms for Coding Interviews

0% completed

Solution: Reverse a String

Problem Statement

Given a string, write a function that uses a stack to reverse the string. The function should return the reversed string.

Examples

Example 1:

Input: "Hello, World!"
Output: "!dlroW ,olleH"

Example 2:

Input: "OpenAI"
Output: "IAnepO"

Example 3:

Input: "Stacks are fun!"
Output: "!nuf era skcatS"

Constraints:

  • 1 <= s.length <= 10<sup>5</sup>
  • s[i] is a printable ascii character.

Solution

The solution to reverse a string can be elegantly achieved using a stack

.....

.....

.....

Like the course? Get enrolled and start learning!
T

traviswlilleberg

· 9 months ago

/* In JavaScript (and possibly other languages), the reversedList array is pointless and creates unnecessary space overhead for the function. You can build a string directly from the stack, like so: */ class Solution { reverseString(s) { if(!s.length) { return s } const stack = s.split(''); let output = ''; while(stack.length) { output += stack.pop(); } return output; } }