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'
100000
O(n)
O(n)
You can see the full challenge with visuals at this link.
Challenges • Asked over 1 year ago by Jake from AlgoDaily
This is the main discussion thread generated for Reverse Only Alphabetical.
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!
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)
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:
This way you don't have to use a regular expression, but I'm not sure of the time complexity? O(N)?
╷
├─ 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).