VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-a-string-without-affecting-special-characters/

⇱ Special array reversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Special array reversal

Last Updated : 26 May, 2026

Given a string str, containing special characters and all the alphabets, reverse the string without affecting the positions of the special characters.

Examples: 

Input:   str = "a,b$c"
Output:  str = "c,b$a"
Explanation: We ignore $ and , and then reverse, so answer is "c,b$a".

Input: str = "A&B"
Output: "B&A"
Explanation: We ignore '&' and then reverse, so answer is "B&A".

[Naive Approach] Using String Reversal Algorithm - O(n) Time and O(n) Space

The idea is to first stores all alphabet characters separately while ignoring special characters. Then, during the second traversal, the alphabets are placed back from the end of the stored array, which reverses only the letters while keeping all special characters at their original positions.

  • Traverse the string and store only alphabet characters in a temporary array.
  • Ignore all special characters while storing the alphabets.
  • Traverse the original string again from left to right.
  • Whenever an alphabet is found, replace it using characters from the temporary array in reverse order.
  • Keep all special characters unchanged at their original positions.
  • Return the final modified string containing reversed alphabets only.

Output
c,b$a

[Expected Approach] Using Two Pointers Approach - O(n) Time and O(1) Space

The intuition behind this approach is to reverse only the alphabet characters while keeping special characters fixed at their original positions. We use the two-pointer technique, where one pointer starts from the beginning and the other from the end of the string. If a pointer encounters a special character, we skip it; otherwise, we swap the alphabet characters. This efficiently reverses only the letters in a single traversal.

  • Initialize two pointers: left at the beginning and right at the end of the string.
  • Traverse the string from both ends until left < right.
  • If the character at left is a special character, move left forward.
  • If the character at right is a special character, move right backward.
  • If both characters are alphabets, swap them and move both pointers inward.
  • Continue this process until all alphabet characters are reversed while special characters remain in their original positions.

Output
c,b$a
Comment
Article Tags: