Reformat Phone Number - Problem
You're building a contact management system and need to standardize phone numbers for consistent display. Given a phone number as a string that contains digits, spaces, and/or dashes, your task is to reformat it according to specific grouping rules.
The Process:
- Remove all spaces and dashes from the input
- Group digits from left to right into blocks of length 3
- When 4 or fewer digits remain, apply special rules:
2 digits: Keep as one block of length 23 digits: Keep as one block of length 34 digits: Split into two blocks of length 2 each
Finally, join all blocks with dashes. The key constraint is that no block should ever have length 1, and at most two blocks can have length 2.
Example: "1-23-45 6" becomes "123-456" (clean โ group into 3s โ format remaining)
Input & Output
example_1.py โ Standard Case
$
Input:
number = "1-23-45 6"
โบ
Output:
"123-456"
๐ก Note:
After removing spaces and dashes: '123456'. We can form one group of 3 ('123') and have 3 remaining digits ('456'), so we keep them as one block of 3.
example_2.py โ Four Remaining Digits
$
Input:
number = "123 4-567"
โบ
Output:
"123-45-67"
๐ก Note:
After cleaning: '1234567'. We form one group of 3 ('123') and have 4 remaining digits ('4567'). Since we can't have blocks of length 1, we split the 4 remaining digits into two blocks of 2: '45' and '67'.
example_3.py โ Short Number
$
Input:
number = "12"
โบ
Output:
"12"
๐ก Note:
After cleaning: '12'. Since we have only 2 digits total, we keep them as one block of length 2.
Constraints
- 2 โค number.length โค 100
- number consists of digits and the characters '-' and ' '
- There are at least two digits in number
Visualization
Tap to expand
Understanding the Visualization
1
Input Cleaning
Remove all non-digit characters (spaces and dashes) from the input string
2
Main Grouping
Create groups of 3 digits from left to right until 4 or fewer digits remain
3
Remainder Handling
Apply special rules: 2โ[2], 3โ[3], 4โ[2,2] to avoid single-digit groups
4
Final Assembly
Join all groups with dash separators to create the formatted phone number
Key Takeaway
๐ฏ Key Insight: The critical rule is avoiding single-digit blocks. When we have 4 remaining digits, we must split them as 2+2 rather than 3+1, ensuring all blocks have length 2 or 3 for optimal readability.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code