Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reversing a string while maintaining the position of spaces in JavaScript
Problem
We are required to write a JavaScript function that takes in a string that might contain some spaces. Our function should reverse the non-space characters while keeping spaces in their original positions.
Understanding the Task
The goal is to reverse only the alphabetic characters while maintaining the exact positions of spaces. For example, "this is normal string" becomes "gnir ts lamron sisiht" - spaces remain at positions 4, 7, and 14.
Example
Following is the code:
const str = 'this is normal string';
const reverseWordsWithin = (str = '') => {
let res = "";
for (let i = str.length - 1; i >= 0; i--) {
if (str[i] != " ") {
res += str[i];
}
if (str[res.length] == " ") {
res += str[res.length];
}
}
return res;
};
console.log(reverseWordsWithin(str));
Output
gnir ts lamron sisiht
How It Works
The algorithm works by iterating through the string backwards and building a result string. When it encounters a non-space character, it adds it to the result. Then it checks if the current position in the original string has a space and adds it to maintain the space positions.
Alternative Approach Using Two Pointers
Here's a cleaner solution using the two-pointer technique:
const reverseWithSpaces = (str) => {
let chars = str.split('');
let left = 0;
let right = str.length - 1;
while (left < right) {
// Skip spaces from left
if (chars[left] === ' ') {
left++;
}
// Skip spaces from right
else if (chars[right] === ' ') {
right--;
}
// Swap non-space characters
else {
[chars[left], chars[right]] = [chars[right], chars[left]];
left++;
right--;
}
}
return chars.join('');
};
console.log(reverseWithSpaces('this is normal string'));
console.log(reverseWithSpaces('a b c d'));
gnir ts lamron sisiht d c b a
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Original Approach | O(n) | O(n) | Complex logic |
| Two Pointers | O(n) | O(n) | Cleaner and intuitive |
Conclusion
Both approaches effectively reverse non-space characters while preserving space positions. The two-pointer method offers better readability and follows a more standard algorithmic pattern for string reversal problems.
