Problem Description
Given a phone number as a string that contains digits, spaces, and dashes, reformat it by first removing all spaces and dashes. Then, group the digits from left to right as follows:
- Form blocks of 3 digits until there are 4 or fewer digits remaining.
- If exactly 4 digits remain, split them into two groups of 2 digits.
- If 2 or 3 digits remain, keep them as a single block. Join the blocks with dashes such that no block is of length 1.
Key Insights
- Clean the input string by filtering out non-digit characters.
- Use greedy grouping: extract blocks of 3 digits until the remaining digits are 4 or fewer.
- Handle the special case when the remaining digits equal 4 by splitting them into two blocks of 2.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input string, because we iterate through the string to remove characters and later to group digits. Space Complexity: O(n), for storing the cleaned digits and resulting groups.
Solution
The solution first removes spaces and dashes from the input string to obtain only the digits. Then, using a loop, it groups digits into blocks of 3 until the remainder is 4 or fewer digits. For a remainder of 4, the digits are split into two groups of 2; for remainders of 2 or 3, they form a single block. The blocks are then concatenated with dashes to form the final formatted phone number. Key data structures are a list (or equivalent) to store the groups and string manipulation functions to extract portions of the digit string.