Reverse a String Algorithm
- Christina Williams
- Dec 11, 2020
- 2 min read
There are several ways you can do the Reverse a String Algorithm. For the purpose of this blog, I am going to talk about this algorithm in JavaScript.
I recently had the experience of a job interview with a whiteboarding challenge online. It was my first, and I was nervous, to say the least. However, I had studied a lot and the interviewer was extremely nice and calming and I just decided I was going to do my best and I took a deep breath, and my nerves just kind of went away.
I was praying beforehand that the Reverse a String Algorithm would be one of my questions because I studied and studied it.... and ... it wasn't!!! But, I am going to talk about it today anyway, as it still relates to my experience for other reasons. Also, just a little advice, write the word function out in your whiteboarding interviews. Not all of the interviewers have studied a lot of JavaScript and may not know "const".
Back to the algorithm --- Reverse a String---
1) This, I think is the easiest way -
--To make a string into an array, we use .split --
--To convert an array into a string, we use .join --
function reverseString(string) {
return string.split("").reverse().join("");
}
console.log(reverseString("hello")); //olleh2) In this option, we are using a decrementing for loop to iterate through every letter of the string and create a new reversed one.
function reverseString(str) {
let string = "";
for (let i = str.length - 1; i > 0; i -- ) {
string += str[i];
}
return string;
}
console.log(reverseString("hello")); //olleh3) You can have a problem that asks you to reverse each word in the sentence. "Welcome to this Javascript Guide!" should be become "emocleW ot siht tpircsavaJ !ediuG". To make a string into an array use .split, then to convert an array to a string use .join.
function reverseString(str) {
let string = "Welcome to this JavaScript Guide!";
// Output becomes !ediuG tpircSavaJ siht ot emocleW
let reverseEntireSentence = reverseBySeparator(string, "");
let reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");
const reverseBySeparator = (string, separator) => {
return string.split(separator).reverse().join(separator);
}There are several more mays to reverse a string. You can look them up. Recursion is also another great method to learn. However, I find that it is smart to learn three ways really well for each algorithm and be able to really explain each step. Don't just memorize the algorithms, but really know and understand them. Not only will they help you become better at JavaScript or whatever language you are learning them in, but they help you become better at coding in general. And for me, they have helped me to become more confident in my coding and interviewing abilities. Yay!




Comments