One Pager Cheat Sheet
- You can
reverseOnlyAlphabeticalcharacters in a given string withlength <= 100000and composed of ASCII characters inO(n)time and space complexity. - The
two pointers with swapmethod is recommended to reverse a regular string. - We can
reverseArraythe alphabetical characters of a string using/[a-zA-Z]/in aforloop to efficiently reverse only the alphabetical characters. - We can swap out alphabetical characters in the string with
elements from our newly created reversedAlphabased on the position/index. - Using the
.mapand.filtermethods, one can reverse only alphabetical characters in a more succinct manner. - We
splitthe string into anarrayand loop over it withmapto return non-alphanumeric characters in their current positions. - We
spliceandjoinour 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.
xxxxxxxxxx84
}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
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.


