Reformat The String - Problem

You are given an alphanumeric string s consisting of lowercase English letters and digits.

You need to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. In other words, no two adjacent characters have the same type.

Return the reformatted string or return an empty string if it is impossible to reformat the string.

Input & Output

Example 1 — Basic Alternating
$ Input: s = "a0b1c2"
Output: "a0b1c2"
💡 Note: Already alternates perfectly: letter-digit-letter-digit-letter-digit pattern, so no changes needed
Example 2 — Need Rearrangement
$ Input: s = "leetcode"
Output: ""
💡 Note: All characters are letters (no digits), so alternating letter-digit pattern is impossible
Example 3 — Mixed Characters
$ Input: s = "1229857369"
Output: ""
💡 Note: All characters are digits (no letters), so alternating letter-digit pattern is impossible

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists of only lowercase English letters and/or digits

Visualization

Tap to expand
Reformat The String INPUT Alphanumeric String s a 0 b 1 c 2 Letters (a,b,c) Digits (0,1,2) Separated: a, b, c 0, 1, 2 Letters: 3, Digits: 3 |3-3| = 0 <= 1 (Valid) s = "a0b1c2" ALGORITHM STEPS 1 Separate Characters Split letters and digits 2 Check Feasibility |letters - digits| <= 1 3 Pick Longer First Larger group starts 4 Interleave Alternate placement a 0 b 1 c 2 Letter-Digit-Letter-Digit... Time: O(n) | Space: O(n) No same-type adjacent! FINAL RESULT Reformatted String: a 0 b 1 c 2 Output: "a0b1c2" Verification: a-0: letter-digit [OK] 0-b: digit-letter [OK] b-1: letter-digit [OK] 1-c: digit-letter [OK] c-2: letter-digit [OK] Valid Reformat! Key Insight: The problem is solvable only if the count difference between letters and digits is at most 1. The group with more characters must start first, then alternate. This ensures no two adjacent characters share the same type (letter-letter or digit-digit). TutorialsPoint - Reformat The String | Optimal Solution
Asked in
Amazon 15 Facebook 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen