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
Reformat Phone Number Single Pass with Smart Logic INPUT Original Phone String: 1 - 2 3 - 4 5 sp 6 Digit (keep) Remove Input String: "1-23-45 6" Extracted Digits: 1 2 3 4 5 6 Total: 6 digits ALGORITHM STEPS 1 Clean Input Remove spaces and dashes 2 Count Digits n = 6 digits total 3 Group by 3s While remaining > 4 digits 4 Handle Remaining 2/3/4 digit rules Final Digit Rules: 2 digits --> [XX] 3 digits --> [XXX] 4 digits --> [XX]-[XX] 6 digits = [XXX]-[XXX] FINAL RESULT Grouping Process: Clean: 123456 Group 1: 123 3 digits Group 2: 456 3 digits Formatted Output: 123 - 456 Output: "123-456" OK - Valid Key Insight: The trick is handling the final 4 digits specially: split into two blocks of 2 instead of one block of 3 + one of 1. This ensures no single-digit blocks. Process greedily by 3s until 4 or fewer remain, then apply the 2/3/4 digit rules for clean formatting. TutorialsPoint - Reformat Phone Number | Single Pass with Smart Logic
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