AlgoDaily 03: Reverse Only Alphabetical

(https://algodaily.com/challenges/reverse-only-alphabetical)[https://algodaily.com/challenges/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:

‘sea!$hells3’

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;
	}).join('')
}

Test cases:

reverseOnlyAlphabetical('sea!$hells3')
// "sll!$ehaes3"

reverseOnlyAlphabetical('1kas90jda3')
//  "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