AlgoDaily 03: Reverse Only Alphabetical


“You are given a string that contains alphabetical characters (a - z, A - Z) and some other characters ($, !, etc.). For example, one input may be:


Can you reverse only the alphabetical ones?”

First thought is to use a stack for this: go through the string forwards, pushing only letters on to the stack. Then go through the positions again, popping the stack for a letter position but leaving non-letters alone:

function reverseOnlyAlphabetical(input) {
	let letterStack = [...input].filter(x => /[a-zA-Z]/.test(x))
	return [...input].map((x) => {
		return /[a-zA-Z]/.test(x) ? letterStack.pop() : x;

Test cases:

// "sll!$ehaes3"

//  "1adj90sak3"

This seems different to the solution given on AlgoDaily, which I actually found hard to follow. The solution there is to get the whole string reversed, then go through swapping the letters for their counterparts in the reversed string, in place.

Tech mentioned