Reformat Phone Number - Problem

You are given a phone number as a string number. The string consists of digits, spaces ' ', and/or dashes '-'.

You need to reformat the phone number in a specific manner:

  1. Remove all spaces and dashes from the input string
  2. Group digits from left to right into blocks of length 3 until there are 4 or fewer digits remaining
  3. Handle the final digits based on how many remain:
    • 2 digits: Create a single block of length 2
    • 3 digits: Create a single block of length 3
    • 4 digits: Create two blocks of length 2 each
  4. Join all blocks with dashes to form the final result

The reformatting process ensures no blocks of length 1 are created and at most two blocks of length 2 appear.

Input & Output

Example 1 — Basic Reformatting
$ Input: number = "1-23-45 6"
Output: "123-456"
💡 Note: Remove dashes and spaces: "123456". Group as 123-456 since we have 6 digits (group first 3, remaining 3 form one block).
Example 2 — Four Digits Special Case
$ Input: number = "123 4-567"
Output: "123-45-67"
💡 Note: Clean to "1234567". Group first 3: "123", leaving 4 digits "4567". Split final 4 into two blocks of 2: "45-67".
Example 3 — Longer Number
$ Input: number = "123 4-5678-90"
Output: "123-456-78-90"
💡 Note: Clean to "1234567890". Group by 3: "123-456-789" leaves 1 digit. Since final 4 digits "7890" should become "78-90".

Constraints

  • 1 ≤ number.length ≤ 100
  • number consists of digits, spaces ' ', and/or dashes '-'

Visualization

Tap to expand
Phone Number Reformatting ProcessStep 1: Input"123 4-5678-90"Step 2: Clean"1234567890"Step 3: Group12345678903 digits3 digits4 remaining → 2+2Step 4: Result"123-456-78-90"
Understanding the Visualization
1
Input
Phone number with spaces and dashes
2
Clean
Extract only digit characters
3
Group
Apply 3-digit grouping with special final rules
4
Output
Formatted number with dash separators
Key Takeaway
🎯 Key Insight: The secret is recognizing that 4 remaining digits must become 2+2 blocks to avoid forbidden single-digit blocks
Asked in
Facebook 15 Google 12 Microsoft 8
23.4K Views
Medium Frequency
~12 min Avg. Time
684 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