One Pager Cheat Sheet
- You can
reverseOnlyAlphabetical
characters in a given string withlength <= 100000
and composed of ASCII characters inO(n)
time and space complexity. - The
two pointers with swap
method is recommended to reverse a regular string. - We can
reverseArray
the alphabetical characters of a string using/[a-zA-Z]/
in afor
loop to efficiently reverse only the alphabetical characters. - We can swap out alphabetical characters in the string with
elements from our newly created reversedAlpha
based on the position/index. - Using the
.map
and.filter
methods, one can reverse only alphabetical characters in a more succinct manner. - We
split
the string into anarray
and loop over it withmap
to return non-alphanumeric characters in their current positions. - We
splice
andjoin
our array to remove unmatched characters and turn it back into a string, resulting in anO(n)
time and space complexity.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
84
}
var assert = require('assert');
​
function reverseOnlyAlphabetical(str) {
const alphaChars = [];
str = str.split(''); // strings are immutable in JS
​
for (let char of str) {
if (/[a-zA-Z]/.test(char)) {
alphaChars.push(char);
}
}
​
const reversedAlpha = reverseArray(alphaChars);
​
let idxRA = 0;
for (let i = 0; i < str.length; i++) {
if (/[a-zA-Z]/.test(str[i])) {
str[i] = reversedAlpha[idxRA++];
}
}
​
return str.join('');
}
​
function reverseArray(arr) {
let start = 0;
let end = arr.length - 1;
​
while (start <= end) {
const temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.