Reverse a string
Reverse a string
Advanced
Instructions
Write a function that takes a string as input and returns the string reversed.
See Solution
Solution
Two-Pointer Approach
const reverseString = (str) => {
let charArray = str.split()
let left = 0
let right = str.length - 1
while(left <= right){
const leftLetter = str[left]
const rightLetter = str[right]
charArray[right] = leftLetter
charArray[left] = rightLetter
left += 1
right -= 1
}
return charArray.join('')
}
Explanation
The function reverseString
takes a string as an argument and returns the reversed string.
We first convert the string into an array of characters using the split()
method.
We then use a two-pointer approach to swap the characters at the left and right ends of the array.
We continue swapping characters until the left pointer is greater than the right pointer.
Finally, we join the array back into a string and return it.
Time Complexity
The time complexity is O(n) because we are iterating through the string once.
Built-in Methods
const reverseString = (str) => {
return str.split('').reverse().join('');
}
Explanation
The split()
method is used to split a string into an array of substrings, and returns the new array.
The reverse()
method is used to reverse the elements in an array.
The join()
method is used to join all elements of an array into a string.
Time Complexity
The time complexity is O(n) because we are iterating through the string once.