Problem 333062 · easy · Phase 03 Linear Management & Searching

Reverse Only the Digits

two pointers · strings

Given a string s, reverse the order of its digit characters while leaving every other character where it is. Return the new string.

Examples

Input:  s = "a1b2c3"
Output: "a3b2c1"

Input:  s = "2024-06-15"
Output: "5160-42-02"
Explanation: the digits 2,0,2,4,0,6,1,5 are written back in reverse into the digit slots.

Constraints

  • 0 <= len(s) <= 10**5
  • Target: O(n) time; one character buffer of size n is fine.

Goals

  • Skip characters that do not satisfy a predicate from both ends
  • Swap matching positions in a mutable buffer
Starting Python…