You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.
You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:
The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.
Return the phone number after formatting.
Example 1:
Input: number = "1-23-45 6" Output: "123-456" Explanation: The digits are "123456". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456". Joining the blocks gives "123-456".
Example 2:
Input: number = "123 4-567" Output: "123-45-67" Explanation: The digits are "1234567". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67". Joining the blocks gives "123-45-67".
Example 3:
Input: number = "123 4-5678" Output: "123-456-78" Explanation: The digits are "12345678". Step 1: The 1st block is "123". Step 2: The 2nd block is "456". Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78". Joining the blocks gives "123-456-78".
Constraints:
2 <= number.length <= 100number consists of digits and the characters '-' and ' '.number.Problem Overview: You receive a phone number string containing digits, spaces, and dashes. The task is to remove separators and regroup the digits so that blocks are mostly of length three, with the last blocks adjusted to avoid a single digit group. The final format must contain groups separated by dashes.
Approach 1: Greedy Grouping (Time: O(n), Space: O(n))
This approach first filters the input to keep only numeric characters. You iterate through the string and append digits to a clean buffer. Once you have the raw digit sequence, grouping is performed greedily: take blocks of three digits while possible. The only exception happens near the end. If exactly four digits remain, split them into two groups of two instead of creating a 3-1 pattern. This rule guarantees that no block has length one.
The key insight is that a phone number formatted with groups of three is optimal for most of the string. Only the final 2–4 digits require special handling. Implementations usually use a loop that processes digits while checking how many remain. When four digits remain, output 2-2 groups instead of 3-1. Because each digit is processed once, the algorithm runs in linear time with O(n) space for the result string.
This solution relies purely on sequential iteration and simple conditional checks. The logic fits naturally within string processing problems and is often categorized under greedy algorithms because each step locally chooses the largest valid group size.
Approach 2: Regular Expressions and String Manipulation (Time: O(n), Space: O(n))
This version also begins by stripping non-digit characters from the input. Instead of manually managing indices, you rely on pattern-based transformations. After extracting digits, logic determines the correct grouping for the tail (2, 3, or 4 digits remaining). Regex can then split the prefix into groups of three using patterns like .{3}, while the remaining digits are appended according to the special-case rules.
The benefit is concise code in languages with strong regex support such as Python or JavaScript. However, under the hood the algorithm still performs a linear scan and substring operations. Complexity remains O(n) time and O(n) space due to intermediate strings.
Regex-based solutions trade explicit control for readability. They are useful when your language provides expressive pattern matching, though most interviewers expect the direct greedy implementation since it shows clear reasoning about the grouping constraints.
Recommended for interviews: The greedy grouping approach is the expected solution. It demonstrates that you understand the constraint preventing single-digit groups and can handle edge cases like four remaining digits. Mentioning the regex alternative shows familiarity with language tooling, but the greedy method communicates stronger algorithmic clarity.
This approach involves removing all spaces and dashes to leave only the digits. Then, greedily group these digits into blocks of size 3. If there are 4 or fewer digits left after grouping, handle them according to the specified rules (4 digits as two blocks of 2, 3 as a single block of 3, and 2 as a single block of 2).
In the C solution, we start by extracting only the digit characters from the input string. We store these digits in a separate character array.
Then, we use a greedy method to group digits into blocks of size 3. We manage the end cases by checking when the remaining digits are 4 or fewer and handle each of these cases accordingly.
Time Complexity: O(n), where n is the length of the input number string.
Space Complexity: O(n), due to the storage for the clean digits and result strings.
First, clean the input string using regular expressions to extract all digits. Then manage the resultant string to construct groups based on the count of remaining digits. Specifically, handle cases with fewer than 5 digits appropriately while using regex or string operations for efficient manipulation and transformations.
This Python solution uses a regular expression to strip non-digit characters from the input. Afterward, we visually segment the digits per the rules, paying special heed to cases where digit chunks end in fewer than five entities, to assure no block of size one occurs.
Python
JavaScript
Time Complexity: O(n), for filtering and reformulation activities.
Space Complexity: O(n), accountable to the digit extraction storage and grouping lists.
First, according to the problem description, we remove all spaces and hyphens from the string.
Let the current string length be n. Then we traverse the string from the beginning, grouping every 3 characters together and adding them to the result string. We take a total of n / 3 groups.
If there is 1 character left in the end, we form a new group of two characters with the last character of the last group and this character, and add it to the result string. If there are 2 characters left, we directly form a new group with these two characters and add it to the result string.
Finally, we add hyphens between all groups and return the result string.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string.
| Approach | Complexity |
|---|---|
| Greedy Grouping | Time Complexity: O(n), where n is the length of the input number string. |
| Using Regular Expressions and String Manipulation | Time Complexity: O(n), for filtering and reformulation activities. |
| Simple Simulation | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Grouping | O(n) | O(n) | General solution for interviews; explicit control over grouping logic |
| Regex + String Manipulation | O(n) | O(n) | Useful in scripting languages where regex simplifies formatting logic |
Reformat Phone Number | Leetcode 1694 | Leetcode Solution • EasyLeetcode • 1,627 views views
Watch 9 more video solutions →Practice Reformat Phone Number with our built-in code editor and test cases.
Practice on FleetCode