Problem Statement
Write a function to reverse a given string.
Example Inputs
- Input:
"hello"
- Output:
"olleh"
JavaScript Method - Using Only String Methods
Approach
To reverse a string in JavaScript, we can use built-in string methods that allow direct manipulation of characters. The approach involves splitting the string into an array, reversing the array, and then joining it back into a string.
Steps
- Use
.split('')
to split the given string into an array of characters.
- Use
.reverse()
to reverse the array.
- Use
.join('')
to join the array back into a reversed string.
Time & Space Complexity
- Time Complexity: O(n), where n is the length of the string, as each character is traversed once.
- Space Complexity: O(n), due to the creation of a new array for characters.
Code Snippet
Dry Run
Example input: "hello"
- Step 1:
str.split('')
→ ['h', 'e', 'l', 'l', 'o']
- Step 2:
['h', 'e', 'l', 'l', 'o'].reverse()
→ ['o', 'l', 'l', 'e', 'h']
- Step 3:
['o', 'l', 'l', 'e', 'h'].join('')
→ "olleh"
Alternative Approach - Without Using JavaScript String Methods
Approach
Another way to reverse a string is by iterating through it from the end to the beginning and building a new reversed string character by character.
Steps
- Initialize an empty string,
reversedStr
.
- Loop from the last character to the first character of the original string.
- Append each character to
reversedStr
in reverse order.
Time & Space Complexity
- Time Complexity: O(n), as we traverse each character once.
- Space Complexity: O(n), since a new string is created to store the reversed characters.
Code Snippet
Dry Run
Example input: "hello"
- Initialize:
reversedStr = ""
- Loop through
"hello"
in reverse order:
- Append 'o' →
reversedStr = "o"
- Append 'l' →
reversedStr = "ol"
- Append 'l' →
reversedStr = "oll"
- Append 'e' →
reversedStr = "olle"
- Append 'h' →
reversedStr = "olleh"
- Final output:
"olleh"
Complexity Analysis
JavaScript Method (Using String Methods)
- Time Complexity: O(n)
- Space Complexity: O(n)
Alternative Approach (Without String Methods)
- Time Complexity: O(n)
- Space Complexity: O(n)
Conclusion
Reversing a string in JavaScript can be achieved using built-in string methods for simplicity or by manually iterating through the string. Both approaches have similar time and space complexities, but the string methods provide a concise and efficient solution.