We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reformat Phone Number

Number: 1812

Difficulty: Easy

Paid? No

Companies: Activision


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.


Code Solutions

# Function to reformat the phone number according to the problem statement.
def reformatNumber(number: str) -> str:
    # Remove spaces and dashes from the input.
    digits = [ch for ch in number if ch.isdigit()]
    result = []
    i = 0
    n = len(digits)
    # Group digits in blocks of 3 until less than or equal to 4 digits remain.
    while n - i > 4:
        # Append block of 3 digits.
        result.append("".join(digits[i:i+3]))
        i += 3
    # Process remaining digits.
    if n - i == 4:
        # Split the 4 digits into two groups of 2 each.
        result.append("".join(digits[i:i+2]))
        result.append("".join(digits[i+2:i+4]))
    else:
        # For 2 or 3 remaining digits, take them as a single block.
        result.append("".join(digits[i:]))
    # Join the groups with dashes.
    return "-".join(result)

# Example usage:
# print(reformatNumber("1-23-45 6"))  # Expected output: "123-456"
← Back to All Questions