Reverse Some Chars

Reverse Some Chars

Reverse only the letters (az, AZ) 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.

Examples

"a-bC-dEf-ghIj"   // → "j-Ih-gfE-dCba"
"ab,cd"           // → "dc,ba"
"1234"            // → "1234"

Walkthrough

Thinking it through

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.

Why a stack is the natural tool here

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.

Separating the two passes

  1. Collection pass: scan once, pushing every letter. Non-letters are ignored entirely.
  2. Reconstruction pass: scan again. At each position, was this a letter originally? If yes, pop and place it. If no, copy the original character unchanged.

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.

Why this beats other approaches

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.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.