Reverse String is a very interesting algorithm question asked in many interviews including FAANG companies.
The question for an algorithm is,
Write a function that reverses a string. The input string should be in reverse order to match the exact.
Example 1:
Input: s = thecodingdev
Output: vedgnidoceht
Example 2:
Input: s = javascript
Output: tpircsavaj
Let's start with the algorithm,
var reverse = function(x) {
var start=0;
var end=x.length-1;
var a='';
//start of the loop until the end becomes less than start
while(end>=start)
{
//combining x[end] with the previous value of a
a=a+x[end];
// end in decrement
end--;
}
return a;
};
Here, we have used a very simple method to reverse a word. We have simply looped the word's character into reverse order and stored it with variable a.
I hope you understood the algorithm if you have and doubt, please let us know in the comments.
0 Comments