× logo Home HTML CSS Javascript React-App Angular logo
logo

Mastering Top 10 Javascript Algorithms

**Algorithm Name**: Reverse String

* **Questions**:
The task is to reverse a given string. The input is a string and the output should also be a string, but in reversed order.

* **Time Complexity**:
- Brute Force: N/A
in this case since there is not much of a way to brute force this problem.

- Optimized:
O(n), you must iterate over each character of the original string once.

* **Space Complexity**:
- Brute Force: N/A
- Optimized:
O(n), you're creating an array with as many elements as there are characters in the string.

* **Approaches**:
- Optimized:
- First, .split('') is used to convert the string into an array where each character of the string is a separate element.
- Then .reverse() is used to reverse the order of the elements in the array.
- Finally, .join('') is used to convert the array back into a string.

- Brute Force: N/A
* **Explanation**:
This function splits the input string into an array of characters, reverses the order of the array, and then joins the elements of the array back into a string. The result is the input string in reversed order.

* **Sample Code**: javascript

- Optimized:

function reverseString(str){
return str.split('').reverse().join('');
}

//Unit Test
console.log(reverseString('facebook'));
let rs =reverseString('hello');
console.log(rs);





logo