String Reversal Approaches in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to reverse a string changes as the string gets longer.
How does the work grow when the input string size grows?
Analyze the time complexity of the following code snippet.
function reverseString(str) {
let reversed = [];
for (let i = str.length - 1; i >= 0; i--) {
reversed.push(str[i]);
}
return reversed.join('');
}
This code creates a new string by adding characters from the end of the input string to the start.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the string once.
- How many times: Exactly once for each character, from the last to the first.
As the string gets longer, the number of steps grows directly with the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows in a straight line with the input size.
Time Complexity: O(n)
This means the time to reverse the string grows directly in proportion to the string length.
[X] Wrong: "Reversing a string is instant or constant time because it's just one operation."
[OK] Correct: Each character must be handled, so the time grows with the string length, not fixed.
Understanding how string reversal scales helps you reason about similar problems with arrays or lists, a common skill interviewers look for.
"What if we used built-in methods like split, reverse, and join? How would the time complexity change?"
Practice
split('') do when applied to a string?Solution
Step 1: Understand the split method
Thesplit('')method splits a string into an array by each character because the separator is an empty string.Step 2: Effect on string
For example,'hello'.split('')becomes['h', 'e', 'l', 'l', 'o'].Final Answer:
It converts the string into an array of individual characters. -> Option DQuick Check:
split('') = array of chars [OK]
- Thinking split('') reverses the string
- Confusing split('') with join()
- Assuming split('') removes spaces
str in JavaScript using built-in methods?Solution
Step 1: Understand string and array methods
Strings do not have areverse()method, but arrays do. So first convert string to array usingsplit('').Step 2: Reverse array and join back
Usereverse()on the array, thenjoin('')to convert back to string.Final Answer:
str.split('').reverse().join('') -> Option BQuick Check:
split + reverse + join = reversed string [OK]
- Trying to call reverse() directly on string
- Using join() before reverse()
- Using incorrect method order
const str = 'abc';
const reversed = str.split('').reverse().join('');
console.log(reversed);Solution
Step 1: Split string into array
'abc'.split('')becomes['a', 'b', 'c'].Step 2: Reverse array and join
['a', 'b', 'c'].reverse()becomes['c', 'b', 'a'], then.join('')makes it'cba'.Final Answer:
'cba' -> Option CQuick Check:
split + reverse + join = 'cba' [OK]
- Expecting original string output
- Expecting array output instead of string
- Confusing method order causing errors
function reverseString(s) {
return s.reverse().join('');
}Solution
Step 1: Check string methods
Strings do not havereverse(), so callings.reverse()causes error.Step 2: Fix by splitting string
We must convert string to array first usings.split('')before reversing.Final Answer:
Strings do not have reverse() method. -> Option AQuick Check:
No reverse() method on strings [OK]
- Trying to reverse string directly
- Ignoring need to split string
- Misunderstanding join() usage
reverseString('hello world') return?function reverseString(s) {
let reversed = '';
for (let i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
return reversed;
}Solution
Step 1: Loop from end to start
The for loop starts at last character index and moves backward to 0, appending each character toreversed.Step 2: Build reversed string
Characters are added in reverse order, so'hello world'becomes'dlrow olleh'.Final Answer:
'dlrow olleh' -> Option AQuick Check:
Loop backward appends chars reversed [OK]
- Looping forward instead of backward
- Not appending characters correctly
- Confusing string concatenation
Ready to prove it?
Pass the test and this pattern moves unknown
