Reverse only the letters (a–z, A–Z) of a string, leaving every
non-letter character fixed in its original position.
reverseSomeChars(s)
A stack makes this clean: push all the letters, then rebuild the string, popping a letter whenever the position originally held a letter.
Input format: a single string.
"a-bC-dEf-ghIj" // → "j-Ih-gfE-dCba"
"ab,cd" // → "dc,ba"
"1234" // → "1234"
The tricky part isn't reversing letters — it's reversing them while leaving every other character exactly where it is. Reversing the whole string would scramble punctuation and digits too. You need two separate concerns: the new order of the letters, and which positions are even allowed to hold one.
Reversing means the last item collected should be the first emitted — last in, first out. Push every letter as you scan left to right, and the rightmost letter ends up on top. Popping hands you letters right to left — already reversed, no index math needed.
Since the stack fills left to right and pops from the top, the first pop gives the last letter of the original, and so on — by the end, every letter position holds its reversed counterpart, and every other position is untouched.
You could extract letters into a list, reverse it, and walk with a descending index — same idea, just without pop operations. The stack framing generalizes: whenever you need to reverse the order you encountered items in while preserving the structure around them, push as you see them, pop when you need them back reversed.
def reverse_some_chars(s):
stack = [ch for ch in s if ch.isalpha()]
out = []
for ch in s:
out.append(stack.pop() if ch.isalpha() else ch)
return "".join(out)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.