Frontend School

Reverse Alphabetic Characters

DSA
medium

Reverse Alphabetic Characters

Medium
String
Two Pointers

Overview

Browserstack frequently deals with text processing, validation, and transformations, especially in scenarios like log analysis, UI element parsing, or test script manipulation. Efficient in-place string transformations are crucial for optimizing performance and resource usage. This problem challenges you to apply the two-pointer technique to selectively reverse parts of a string while maintaining the structure of other parts, a common pattern in text manipulation tasks.

What you need to do / Task

Implement a function reverseAlphabetic that takes a string s as input. The function should transform the string such that only its alphabetic characters (case-sensitive) are reversed. All non-alphabetic characters (digits, symbols, spaces, etc.) must remain in their original positions within the string.

Input & output

  • Input: s: A string consisting of printable ASCII characters.
  • Output: A string, the transformed version of s where only alphabetic characters are reversed, and non-alphabetic characters retain their original positions.

Clarifications

  • An empty input string (s = "") should return an empty string.
  • The input string s can contain any printable ASCII character.
  • 'Alphabetic' means 'a'-'z' and 'A'-'Z'. Case sensitivity matters for character identification, but when reversing, 'A' will swap with 'z' if they are the next alphabetic characters to be swapped.

Examples

1

Example 1

Input:

s = "ab-cd"

Output:

"dc-ba"

Note:

The alphabetic characters 'a', 'b', 'c', 'd' are reversed to 'd', 'c', 'b', 'a'. The hyphen '-' remains in its original position.

2

Example 2

Input:

s = "a-bC-dEf-ghIj"

Output:

"j-Ih-gFe-dCbA"

Note:

All alphabetic characters are reversed while non-alphabetic characters keep their positions.

3

Example 3

Input:

s = "Test1ng-Str1ng"

Output:

"gn1rtS-gnitTse"

Note:

Digits and hyphens are ignored. Only letters ('T','e','s','t','n','g','S','t','r','n','g') are reversed.

Constraints

Constraints & assumptions

  • 1 <= s.length <= 10^5
  • s consists of printable ASCII characters.

Out of scope

  • Handling Unicode characters beyond basic ASCII.
  • Optimizing for extreme memory constraints (assume standard string operations are fine).

What interviewers evaluate

  • Correct application of the two-pointer technique for in-place string manipulation.
  • Edge case handling (empty string, string with no alphabetic characters, string with only alphabetic characters).
  • Code clarity, readability, and efficient character checking.
  • Time and space complexity analysis.

Loading editor...