### Community

##### Notifications
You’re not receiving notifications from this thread.

### Reverse Only Alphabetical (Main Thread)

Here is the interview question prompt, presented for reference.

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?

```js reverseOnlyAlphabetical('sea!\$hells3'); // 'sll!\$ehaes3' ```

### Constraints

• Length of the given string <= `100000`
• The string comprises of ASCII characters
• Expected time complexity : `O(n)`
• Expected space complexity : `O(n)`

You can see the full challenge with visuals at this link.

Challenges • Asked over 1 year ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Jul 09, 2019:

This is the main discussion thread generated for Reverse Only Alphabetical.

Jake from AlgoDaily Commented on Jul 09, 2019:

Hi @mattvanwinkle:disqus - thanks so much for catching this. I've updated the test cases to be correct.

For those reading-- in the original solution, in the second for-loop, I was not using a separator index to track the elements in `reversedAlpha`. Hence, the letters were incorrectly placed. My bad!

John Commented on Jul 13, 2019:

I was a bit stumped by this one - shouldn't the the reversedAlpha array would have less indices than the original string if the original string contained characters?i.e. - input string - 'h!ey'reversedAlpha = ['y', 'e', 'h'];so on the 4th iteration over this string wouldn't it return `undefined` for the character to swap?

update - ahh, I see! the solution you use has a separate index for that (as mentioned in your comment)

Anonymous Commented on Feb 12, 2020:

Hi, I'm using Python but it seems one can use the 2 pointer technique (as mentioned) for this problem. So the algorithm would be something like:

1. Create a pointer at the beginning (i)
2. Create a pointer at the end (j)
3. Check if i and j are alphabetical characters
4. If they are then swap
5. If they're not then don't swap and either increment i or decrement j

This way you don't have to use a regular expression, but I'm not sure of the time complexity? O(N)?

Anonymous Commented on Sep 17, 2020:

├─ JUnit Jupiter ✔
└─ JUnit Vintage ✔
└─ MainTest ✔
├─ firstTest ✘ expected:<[[s, l, l, !, \$, e, h, a, e, s, 3]]> but was:<[sll!\$ehaes3]>
└─ secondTest ✘ expected:<[[1, a, d, j, 9, 0, s, a, k, 3]]> but was:<[1adj90sak3]>

Isn't the function supposed to return a single string? The characters are in the correct order but the tests fail due to difference in representation.. (I am returning a String as it is set by default return type).