Function to reverse a string JavaScript


In this problem statement, our target is to print the n consecutive odd numbers and implement this problem with the help of Javascript functionalities. So we can solve this problem with the help of loops in Javascript.

Understanding the problem statement

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”, the reverse of this string will be “olleH”.

Logic for the given problem

For solving the above problem we need to have the basic knowledge of Javascript. In the code we will use a Javascript function to reverse the given string and pass the string in the function. Inside this function we will create a variable to store the reversed string and use a for loop to iterate through the characters of the input string in reverse order and put these reversed strings in the created 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.

Code for the algorithm

//function to reverse the given string
function reverseStr(str) {
   let reverse = '';
   for (let i = str.length - 1; i >= 0; i--) {
      reverse += str[i];
   }
   return reverse;
}
const str = "Hello Javascript";
console.log(reverseStr(str));

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. The time and space complexities of this algorithm are O(n).

Updated on: 18-May-2023

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements