Step 3: The Replacement Dance
Dealing with Matched Characters
When a character matches our Regular Expression (it's an alphabet), we turn to our alphaOnly
array. We pull out the last character from this array using splice
and use it for the swap. This way, each loop iteration places a unique reversed alphabetical character back into the original string.
Stitching It Back Together
Finally, we use the join('')
method to transform our array back into a string, effectively reversing only the alphabetical characters while leaving all others intact.
Complexity of the Final Solution
Time Complexity
Our final solution maintains a time complexity of O(n)
, where n
is the total number of characters in the input string. Each loop iteration, as well as the filter
and map
functions, work in linear time, keeping the process efficient.
Space Complexity
The space complexity also stands at O(n)
because we use an auxiliary array (alphaOnly
) to temporarily store the alphabetical characters.
xxxxxxxxxx
let alphaOnly = str.split('').filter(c => /[a-z]/gi.test(c));
return str.split('').map( c => {
if (/[^a-z]/gi.test(c)) {
return c;
}
​
let next = alphaOnly[alphaOnly.length - 1];
​
alphaOnly.splice(alphaOnly.length - 1, 1);
​
return next;
}).join('');