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 String: Create Alternating PatternInput: "a12bc2"a12bc2Separate: Letters = [a,b,c] (3), Digits = [1,2,2] (3)Count difference = |3-3| = 0 ≤ 1 ✓ Alternation possible!Output: "a1b2c2"a1b2c2Perfect alternation!
Understanding the Visualization
1
Input
Mixed string with letters and digits: "a12bc2"
2
Process
Separate into groups and check if alternation is feasible
3
Output
Alternating pattern or empty string if impossible
Key Takeaway
🎯 Key Insight: Alternating letter-digit pattern is only possible when the difference between letter count and digit count is at most 1
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