Skip to main content

Reformat Phone Number - Solution & Explanation

EasyString18 min readAsked at: Activision
Practice this problem

Problem Statement

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:

  • 2 digits: A single block of length 2.
  • 3 digits: A single block of length 3.
  • 4 digits: Two blocks of length 2 each.

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 <= 100
  • number consists of digits and the characters '-' and ' '.
  • There are at least two digits in number.

Approach Overview

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.

Approach 1: Greedy Grouping

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

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.

Try this approach in the editor →

Approach 2: Using Regular Expressions and String Manipulation

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.

Code

Python

JavaScript

Complexity

Time Complexity: O(n), for filtering and reformulation activities.
Space Complexity: O(n), accountable to the digit extraction storage and grouping lists.

Try this approach in the editor →

Approach 3: Simple Simulation

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.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Greedy Grouping

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.

Using Regular Expressions and String Manipulation

Time Complexity: O(n), for filtering and reformulation activities.
Space Complexity: O(n), accountable to the digit extraction storage and grouping lists.

Simple Simulation

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy GroupingO(n)O(n)General solution for interviews; explicit control over grouping logic
Regex + String ManipulationO(n)O(n)Useful in scripting languages where regex simplifies formatting logic

Video Solution

Reformat Phone Number | Leetcode 1694 | Leetcode SolutionEasyLeetcode1,629 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Reformat Phone Number easy or hard?
Reformat Phone Number is classified as an Easy problem on LeetCode with an acceptance rate around 67%. The main challenge is handling the edge case where four digits remain so that the output avoids a single-digit group.
Reformat Phone Number Python/Java solution
Both Python and Java implementations follow the same idea: strip non-digit characters, iterate through digits, and build groups using conditional checks on the remaining length. Python often uses list joins for efficiency, while Java typically uses a StringBuilder.
How to solve Reformat Phone Number in O(n)?
First iterate through the input and collect only numeric characters. Then process the digit string greedily: append groups of three digits separated by dashes until the remaining digits are 2–4. If four digits remain, split them into 2-2 groups; otherwise keep the remaining group as size 2 or 3. Each digit is processed once, giving O(n) complexity.
What is the best approach for Reformat Phone Number?
The greedy grouping approach is the best solution. First remove spaces and dashes to extract only digits, then form groups of three while possible. If four digits remain, split them into two groups of two to avoid a single-digit block. This runs in O(n) time and O(n) space.
Is Reformat Phone Number asked at Google/Amazon/Meta?
Problems like Reformat Phone Number appear in interviews focused on string manipulation and formatting logic. Variants of string grouping and formatting have shown up in coding rounds at companies such as Amazon and Google, especially for entry-level and screening interviews.
What data structure is used in Reformat Phone Number?
The solution primarily uses string processing with a dynamic buffer or string builder. You store digits in a temporary string or array, then append grouped segments to the result. No complex data structures are required beyond basic string manipulation.
What is the time complexity of Reformat Phone Number?
The optimal solution runs in O(n) time where n is the length of the input string. You scan the string once to collect digits and once more to create formatted groups. Space complexity is O(n) for storing the cleaned digits and final formatted output.

Ready to solve this problem?

Practice Reformat Phone Number with our built-in code editor and test cases.

Practice on FleetCode