LeetCode Problem Workspace
Reformat Phone Number
Reformat a phone number by removing spaces and dashes, grouping digits into blocks of 3 or 2, and joining them with dashes.
1
Topics
6
Code langs
3
Related
Practice Focus
Easy · String-driven solution strategy
Answer-first summary
Reformat a phone number by removing spaces and dashes, grouping digits into blocks of 3 or 2, and joining them with dashes.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for String-driven solution strategy
The task involves reformatting a phone number by first removing spaces and dashes, then grouping the digits into blocks of 3 or 2. The solution leverages a string-driven approach to ensure the proper reformatting of the number. The digits are grouped and joined according to specific rules, without leaving any block of length 1 or exceeding two blocks of length 2.
Problem Statement
You are given a phone number represented as a string, which consists of digits, spaces, and dashes. The objective is to reformat this phone number by removing spaces and dashes first. Then, the remaining digits should be grouped into blocks of 3 until there are 4 or fewer digits remaining. The final remaining digits are grouped into blocks of length 2 if needed, ensuring no block of length 1.
After grouping the digits, the blocks are joined together using dashes. Note that no block should have a length of 1, and there can be at most two blocks of length 2. The task requires careful handling of string operations and proper digit grouping to ensure the reformatting adheres to the rules.
Examples
Example 1
Input: number = "1-23-45 6"
Output: "123-456"
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"
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"
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.
Solution Approach
Remove non-digit characters
The first step in solving this problem is to remove all spaces and dashes from the input string. This can be efficiently done using string replacement operations or regular expressions. Once the non-digit characters are removed, we are left with just the digits of the phone number.
Group digits into blocks of 3
Next, we need to group the digits into blocks of length 3. We will iterate through the digits, adding groups of 3 digits to the result until fewer than 4 digits remain. If there are fewer than 4 digits remaining, we need to split them into blocks of length 2.
Handle the final groupings
For the remaining digits (if any), we need to group them into blocks of length 2, making sure no block ends up with a length of 1. If exactly 4 digits remain, they should be split into two blocks of 2 digits each. Finally, join all blocks with dashes to produce the final formatted result.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
The time complexity depends on the number of digits in the input string. After removing spaces and dashes, the algorithm needs to group digits and join them with dashes, which results in linear time complexity, O(n), where n is the number of digits. The space complexity is also O(n) since we store the digits and the formatted phone number in memory.
What Interviewers Usually Probe
- Looking for a candidate to demonstrate knowledge of string manipulation techniques.
- Testing the candidate's ability to break down a problem into manageable steps for digit grouping and reformatting.
- Evaluating the candidate’s understanding of edge cases, such as handling blocks of length 1 or 2.
Common Pitfalls or Variants
Common pitfalls
- Forgetting to remove non-digit characters first, leading to incorrect results or errors in grouping.
- Improperly handling the final groupings, resulting in invalid block sizes (e.g., a block of length 1).
- Failing to account for the possibility of having exactly 4 digits left, which must be split into two blocks of 2 digits.
Follow-up variants
- Handling phone numbers with special characters other than dashes and spaces.
- Reformatting a phone number where the final block consists of exactly 1 digit.
- Adapting the solution to different phone number formats, such as country codes.
FAQ
How do I approach reformatting the phone number in this problem?
Start by removing non-digit characters (spaces and dashes), then group the remaining digits into blocks of 3, ensuring the final block sizes are valid.
What should I do if the final number has fewer than 4 digits remaining?
If fewer than 4 digits remain, group them into blocks of length 2. Ensure that no block ends up with a length of 1.
What is the primary pattern for solving this problem?
This problem follows a string-driven solution strategy, focusing on string manipulation and grouping operations.
Can GhostInterview help me with similar string-driven problems?
Yes, GhostInterview can guide you through similar string manipulation problems, providing structured approaches and identifying common pitfalls.
What are the edge cases I should consider for this problem?
Consider edge cases like handling a phone number with exactly 4 digits remaining, and making sure no block has a length of 1.
Solution
Solution 1: Simple Simulation
First, according to the problem description, we remove all spaces and hyphens from the string.
class Solution:
def reformatNumber(self, number: str) -> str:
number = number.replace("-", "").replace(" ", "")
n = len(number)
ans = [number[i * 3 : i * 3 + 3] for i in range(n // 3)]
if n % 3 == 1:
ans[-1] = ans[-1][:2]
ans.append(number[-2:])
elif n % 3 == 2:
ans.append(number[-2:])
return "-".join(ans)Continue Topic
string
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
String-driven solution strategy
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Easy
Stay on this level to stabilize interview delivery.
arrow_forward