DEV Community

Cover image for Reverse a String Algorithm
Ruben Alvarado
Ruben Alvarado

Posted on

Reverse a String Algorithm

If you've been following me, you already know about arrays and how to measure an algorithm. So, it's showtime! Let's write our first algorithm in Javascript.

I'm assuming you're new to algorithms or looking to refresh your skills. In this series, I'll cover the 10 most common algorithms asked in technical interviews, starting with the basics and building from there.

Let me introduce you to the simplest and most frequently asked algorithm in tech interviews, the good old reverse a string.

gnirts a esreveR

For this series, I'll follow a consistent approach: first explaining the problem statement, then the algorithm to solve it, and finally the implementation. This structure helps train your mind to tackle problems methodically in technical interviews. Remember, practice is the only way to master these skills.

You could brute force your way through until something works, but taking a more structured approach is better when dealing with algorithms, since an algorithm is, by definition, a step-by-step solution.

Problem statement

Since this is a simple algorithm, the problem statement will be brief. However, as I mentioned earlier, we're training our minds to approach algorithms systematically.

Given a string as input, write a function that returns the input string reversed

Easy, right? Let's analyze what they're asking. First, the problem statement already defines an input and an output:

  • Given a string as input
  • returns the input string reversed

To go from input to output, we need to write a function that reverses the string. We need to define a function that performs this task, and for that, we need to develop an algorithm.

I'm emphasizing this approach because mastering it will significantly improve your performance and help you pass coding interviews. This systematic method is what separates successful candidates from those who struggle. I'm confident that with this approach, you'll significantly improve and become the next Soham Parekh.

Algorithm to solve it

Let's look at how we can convert Hello world! to !dlrow olleH. We need to create a step-by-step solution for this process. The algorithm below uses Javascript, but you can adapt it to other programming languages. The step-by-step processes this way:

  • Validate input: Check if the string is empty or null before processing it.
if(str.length === 0 || !str){
    return; // or throw an error.
}
Enter fullscreen mode Exit fullscreen mode
  • Convert the string to an array: In JavaScript, we can convert a string into an array of characters using the split method. This approach allows us to handle each character as an individual element in the array.
const stringAsArray = str.split('');
Enter fullscreen mode Exit fullscreen mode
  • Reverse the array: Now that we have an array of characters, we can reverse it by swapping positions. This means the character in position 0 becomes the last one, and so on. There are two approaches to accomplish this: using the built-in reverse method for arrays or looping through each position. I'll show you both methods so you can choose the one that works best for you.
// with the reverse built-in method
const reversedArray = stringAsArray.reverse();

// with loop

// declared new array to store chars
const reversedArray = [];

// loop through the array in reverse order starting from the end
for (let i = stringAsArray.length - 1; i >= 0; i--) {
        // then, push to the new array
    reversedArray.push(stringAsArray[i]);
}
Enter fullscreen mode Exit fullscreen mode
  • Convert the array back to a string: Finally, we need to return the new array as a string, and for this we can use the built-in join() method.
return reversedArray.join('');
Enter fullscreen mode Exit fullscreen mode

Voilà! You now have the complete algorithm to reverse a string in JavaScript. Don't forget to mention me in your acknowledgments when you land that job at Google!

Typescript implementation

Here's the complete implementation in Typescript to highlight data types:

// with built-in methods
function reverseString(str: string): string {
  return str.split("").reverse().join("");
}
// with loop
export function reverseStringWithLoop(str: string): string {
  const stringAsArray = str.split("");
  const reversedArray = [];
  for (let i = stringAsArray.length - 1; i >= 0; i--) {
    reversedArray.push(stringAsArray[i]);
  }
  return reversedArray.join('');
}
Enter fullscreen mode Exit fullscreen mode

Remember, though: you should understand how the algorithm works before using the fancy one-liner approach.

Conclusion

Understanding an algorithm is better than just memorizing it. This approach can help you comprehend more complex algorithms later. Strong fundamentals are key here; if you master the basics, you can tackle greater complexities.

Next time, we'll tackle the is palindrome algorithm, which is frequently used in interviews and relies on reversing a string. Feel free to comment if you'd like me to provide a step-by-step explanation of another algorithm.

For reference, I've created a GitHub repository containing all the algorithms we'll cover in this series: https://github.com/RubenOAlvarado/algorithms

Cover picture belongs to 愚木混株 Yumu in Unsplash

Top comments (0)