Reverse a given string, also using similar technique reverse a sentence without reversing words

Reverse a given string

Input : A string // 'Hello'
Output : A string // 'olleH'


There are many ways of reversing a string.

Approach 1 : Simplest way is to use inbuilt javascript methods.

Logic :

  • Convert a given string into an array using String.prototype.split() with appropriate separator.
  • Reverse a newly formed array using Array.prototype.reverse().
  • Convert a given array back to string Array.prototype.join() with appropriate separator.

Solution :


Approach 2 : If you are not allowed to use the inbuilt methods of JavaScript then you can use this approach. This approach is computationally efficient compared to approach1.

Logic :

  • Iterate over first string from the right most character to the left most character and append those characters.

Solution :


Reverse a given multiple words string without reversing the words

Input : A string with mutiple words // 'This is cat'
Output : A string // 'cat is This'

Logic :
There are many ways of reversing a multiple words string, simplest way is to use inbuilt javascript methods.
We will use the similar logic as described in the previous question.

Solution :

Further reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *