Reformat The String - Problem
The Alternating Pattern Challenge!

You're given an alphanumeric string containing lowercase letters and digits mixed together. Your mission is to rearrange these characters so that no two letters are adjacent and no two digits are adjacent.

Think of it like creating a perfect alternating pattern: a1b2c3 or 1a2b3c. Each letter must be surrounded by digits, and each digit must be surrounded by letters.

Goal: Return any valid reformatted string, or an empty string "" if it's impossible to create such an arrangement.

Examples:
"a0b1c2""a0b1c2" (already alternating!)
"leetcode""" (impossible - no digits)
"a1b2""a1b2" or "1a2b"

Input & Output

example_1.py — Basic alternating pattern
$ Input: s = "a0b1c2"
Output: "a0b1c2"
💡 Note: The string already alternates perfectly between letters and digits, so no rearrangement is needed.
example_2.py — Impossible case
$ Input: s = "leetcode"
Output: ""
💡 Note: The string contains only letters and no digits. Since we need alternating pattern, it's impossible to arrange.
example_3.py — Rearrangement needed
$ Input: s = "1229857369"
Output: ""
💡 Note: The string contains only digits and no letters. Alternating arrangement requires both types, so it's impossible.

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists of only lowercase English letters and/or digits
  • The string is guaranteed to be non-empty

Visualization

Tap to expand
The Alternating Dance PatternInput Analysis: "a1b2c34"a1b2c34Counting PhaseLettersabc= 3Digits1234= 4Feasibility Check|4 - 3| = 1 ≤ 1 ✓Dance is possible!Final Dance ArrangementDigits are more frequent → Start with digit1a2b3c4"1a2b3c4"
Understanding the Visualization
1
Count the Dancers
Separate letters and digits, count each type
2
Check if Dance is Possible
If counts differ by more than 1, perfect alternation is impossible
3
Start with the Larger Group
The more frequent type goes first to ensure proper alternation
4
Alternate Perfectly
Place characters in alternating pattern: type1-type2-type1-type2...
Key Takeaway
🎯 Key Insight: Perfect alternation is only possible when the counts of letters and digits differ by at most 1. Always start with the more frequent type!
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~12 min Avg. Time
985 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