Have you ever found yourself staring at a string, wondering how to reverse its order? Today, we shall explore many approaches one can take to solve it including two pointers. If you’re not familiar with two-pointers, don’t worry, it’s a clever way to manipulate arrays (and strings!) that involves keeping track of two indices at once. And don’t worry, I promise not to get too pointed in my explanation (I couldn’t resist a pun). So sit back, relax, and Let’s dive in!
Problem Statement:
Write a function that reverses a string.
Approach 1: Brute Force
- We can create an empty string, then loop through the input string from end to start and concatenate each character to the new string.
// ES6 Arrow Function
const reverseString = str => {
let reversed = '';
for(let i = str.length; i >= 0; i--) {
reverseString += str[i];
}
return reverseString;
}
Time Complexity: O(N)
Space Complexity: O(N)
Approach 2: Two Pointers
We can use two pointers, one starting from the beginning of the string and one starting from the end.
We swap the characters at each index until the two pointers meet in the middle.
Note: Elements at each pointer are swapped using array destructuring.
// ES6 Arrow Function
const reverseString = str => {
let i = 0, j = str.length - 1;
while(i <= j) {
[str[i], str[j]] = [str[j], str[i]];
i++;
j--;
}
return str;
}
Time Complexity: O(N)
Space Complexity: O(1)
Note: In addition to the two-pointers approach, there are two other methods to solve this problem in JavaScript: using built-in methods and using recursion. While both of these methods have a time and space complexity of linear order, the most efficient method is the two-pointers approach. Nevertheless, for the sake of completeness, solutions for both of these methods are also presented below.
Approach 3: Built-in Methods
JavaScript provides a built-in method called
reverse()
that can be used to reverse an array.Since strings in JavaScript can be treated like arrays of characters, we can convert the string to an array, reverse the array, and then convert it back to a string.
// ES6 Arrow Function
const reverseString = str => {
return str.split('').reverse().join('');
}
Time Complexity: O(N)
Space Complexity: O(N)
Approach 4: Recursion
We can recursively reverse the substring that excludes the first character, and then concatenate the first character at the end.
// ES6 Arrow Function
const reverseString = str => {
if(str === '') return '';
else return reverseString(str.substr(1)) + str.charAt(0);
}
Time Complexity: O(N)
Space Complexity: O(N)
And there you have it guys! We’ve explored different approaches, optimized our solutions, and hopefully had some fun along the way. I hope this article has provided you with valuable insights and helped you better understand the different approaches to solving this problem. Happy coding!