How to reverse a string using only one variable in JavaScript


In this problem statement, our target is to print the reverse string using only one variable and implement the solution with the help of Javascript. So we can solve this problem with the help of loops in Javascript.

Understanding the problem

The given problem is stating that we have given a string to which we have to reverse the string. In simple terms we can say that if we have the string “Hello World”, the reverse of this string will be “dlroW ,olleH”.

Logic for the given problem

In order to reverse the given string with only one variable we will have to start creating an empty string variable. And then we will iterate using the for loop from the last character to the first character. In this phase we will append the current character to the reversed variable. And after traversing all the characters the reversed string will be achieved. So by iterating through the given input string in reverse order and by appending every character to the reversed variable we can efficiently reverse the string using only one variable.

Algorithm

Step 1: Starting point of this algorithm is to declare a variable for storing the reverse string and initialize it as empty.

Step 2: After declaring the variable, iterate through the characters of the string with the help of a for loop. So here we will iterate the string from the last character because we want the string in reverse order.

Step 3: Inside this loop, we will append all the traversed characters in the variable created in step 1.

Step 4: At the end we will show the outcome of the function as a reversed string.

Example

//function to get the reversed string
function reverseStr(str) {
   var reversed = '';
   //iterate the string with a loop
   for (var i = str.length - 1; i >= 0; i--) {
      reversed += str[i];
   }
   
return reversed;
   }
 
var actualString = 'Hello, Tutorials Point!';
var reversedStr = reverseStr(actualString);
console.log(reversedStr);

Output

!tnioP slairotuT ,olleH

Complexity

The time taken by the code to execute and produce the reverse string is O(n), because we need to iterate the string once with the help of a for loop to reverse the given string. In this n is the length of the given string. And the space complexity for storing the reversed string is also O(n), because we are storing all the characters in the string variable which is the same length of the input string.

Conclusion

In the above mentioned code we have defined a function to reverse the given string. This function is basically taking an argument as a string and giving the generated output as the reverse of the input string with the same length.

Updated on: 14-Aug-2023

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements