Taro Logo

Reformat Phone Number

Easy
Asked by:
Activision
0 views
Topics:
Strings

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the length range of the input string, and can it be completely empty or consist only of spaces and dashes?
  2. If the total number of digits is 4, should it be formatted as two blocks of 2 (e.g., '12-34') rather than a block of 3 and a block of 1?
  3. Are there any specific constraints on the maximum length of the input phone number string?
  4. Can the input string contain characters other than digits, spaces, and dashes?
  5. When grouping the final digits into blocks of 2 or 3, does the priority go to 3-digit blocks first or 2-digit blocks first when a remainder of 4 digits is left?

Brute Force Solution

Approach

Imagine you have a messy string of digits and dashes that you need to clean up and group nicely. The brute force approach involves completely stripping away the existing formatting and then exploring every possible way to chop the remaining numbers into standard chunks of two or three digits.

Here's how the algorithm would work step-by-step:

  1. First, collect all the actual numbers by ignoring every single dash and space found in the original text.
  2. Then, try dividing this long sequence of digits into blocks where each block has either two or three digits.
  3. Check different combinations of these two-digit and three-digit blocks to see which arrangements use up all the numbers without leaving any stray digits behind.
  4. Make sure that any leftover digits at the very end are neatly grouped into a final block of two or three numbers according to the standard grouping rules.
  5. Compare all the valid arrangements you generated by trying out the different block sizes.
  6. Finally, pick the arrangement that follows the required grouping pattern and join the blocks together with dashes to get the final cleaned-up version.

Code Implementation

def reformatNumber(phone_string):
    # Extract only digits because dashes and spaces do not contribute to the grouping count
    clean_digits = ''.join([character for character in phone_string if character.isdigit()])

    digit_total_length = len(clean_digits)

    block_groups = []

    current_index = 0

    # Process digits in chunks until four or fewer remain to handle edge cases properly
    while digit_total_length - current_index > 4:
        block_groups.append(clean_digits[current_index:current_index + 3])

        current_index += 3

    remaining_count = digit_total_length - current_index

    # Split remaining digits into twos or threes depending on the leftover count
    if remaining_count == 4:
        block_groups.append(clean_digits[current_index:current_index + 2])

        block_groups.append(clean_digits[current_index + 2:current_index + 4])

    else:
        block_groups.append(clean_digits[current_index:])

    # Join all formatted blocks with dashes to construct the final telephone number
    return '-'.join(block_groups)

Big(O) Analysis

Time Complexity
O(2^(n/3)) – Filtering out spaces and dashes from the input string of length n takes linear time, leaving a sequence of up to n digits. Exploring every possible combination of two-digit and three-digit block partitions requires traversing a binary-like recursive decision tree with a depth proportional to n/3. At each step, we branch out to test different groupings until all digits are consumed, which scales exponentially with the number of digits. This exponential exploration approximates operations proportional to 2^(n/3), which simplifies to O(2^(n/3)).
Space Complexity
O(n) – To determine the space complexity, let N represent the length of the input string containing digits, spaces, and dashes. The algorithm first collects all valid digits by stripping away spaces and dashes, storing them in an auxiliary string or character list that scales linearly with the input size. Additionally, the final formatted output requires a new string of size proportional to N, as it introduces dashes interspersed among the digits. Therefore, the extra memory used by the temporary character collection and the resulting formatted string grows directly in proportion to N, resulting in an auxiliary space complexity of O(n).

Optimal Solution

Approach

The solution reformats a given phone number by first stripping out all spaces and dashes to keep only the digits. It then extracts digits into chunks of three as long as more than four digits remain. Finally, any remaining two to four digits are partitioned into groups of two or three as specified and joined with hyphens.

Here's how the algorithm would work step-by-step:

  1. Iterate through the input string and collect all digit characters into a list.
  2. Maintain an index pointer to track the current position in the digit list.
  3. Extract blocks of three digits and append them to a list while more than four digits remain.
  4. Examine the remaining count of digits, splitting four digits into two pairs of two, or keeping two or three digits as a single block.
  5. Join all assembled blocks with dashes and return the final formatted string.

Code Implementation

def reformat_number(number: str) -> str:
    # Filter out all non-digit characters from the input
    digits = [char for char in number if char.isdigit()]
    blocks = []
    index = 0
    total_digits = len(digits)
    # Process digits in groups of three while more than four remain
    while total_digits - index > 4:
        blocks.append("".join(digits[index:index + 3]))
        index += 3
    # Group the remaining four or fewer digits according to the rules
    remaining = total_digits - index
    if remaining == 4:
        blocks.append("".join(digits[index:index + 2]))
        blocks.append("".join(digits[index + 2:index + 4]))
    else:
        blocks.append("".join(digits[index:]))
    # Join all formatted blocks using dashes
    return "-".join(blocks)

Big(O) Analysis

Time Complexity
O(n) – Extracting the digits and iterating through them to form blocks each take linear time with respect to the length of the input string.
Space Complexity
O(n) – Linear auxiliary space is used to store the extracted digits and the formatted string blocks.

Edge Cases

Input string contains only spaces and dashes with no digits
How to Handle:
After stripping non-digit characters, the resulting empty string falls through the block formatting logic and returns an empty string.
Input consists of exactly 2 digits
How to Handle:
The algorithm skips the 3-digit block logic and returns the 2 digits as a single valid block without any dashes.
Input consists of exactly 3 digits
How to Handle:
The algorithm processes the sequence as a single 3-digit block and returns it directly without inserting dashes.
Input consists of exactly 4 digits
How to Handle:
Instead of creating a trailing 1-digit block, the algorithm forms two separate 2-digit blocks separated by a single dash.
Input contains a large number of digits up to the maximum constraint limit
How to Handle:
A linear scan to filter characters followed by an iterative chunking approach ensures optimal O(N) time and space complexity without scaling issues.
Input string has a length resulting in a remainder of 1 when grouped by 3
How to Handle:
The algorithm handles this by processing the final four digits as two groups of 2-digit blocks to avoid any invalid 1-length blocks.
Input already has correct formatting with existing dashes and spaces
How to Handle:
The initial cleanup phase strips all non-digit characters, ensuring pre-existing formatting does not interfere with the final output structure.