Reformat Phone Number

The task is to remove all spaces and dashes from the given phone number and reformat it. The number should be divided into groups of three digits. If at the end we have one or two digits, we leave them as they are. If we have four digits, we split them into two groups of two digits.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
    def reformatNumber(self, number: str) -> str:
        # Initialize a list to store the digits
        digits = []

        # Loop over each character in the number string
        for char in number:
            # If the character is a digit, append it to the digits list
            if char.isdigit():
                digits.append(char)

        # Initialize result
        result = []

        # Iterate over the digits
        while len(digits) > 4:
            # Add the next three digits to the result
            result.append(''.join(digits[:3]))
            # Remove these digits
            digits = digits[3:]

        # If there are four digits left, split them into two groups
        if len(digits) == 4:
            result.extend([''.join(digits[:2]), ''.join(digits[2:])])
        else:
            result.append(''.join(digits))

        # Join the groups with dashes
        return '-'.join(result)

This solution works as follows:

  1. It creates a list of digits by iterating over the characters in number and keeping only the digits.

  2. It creates an empty list result to hold the groups of digits.

  3. It uses a while loop to process the digits. As long as there are more than four digits left, it takes the next three digits, joins them into a string, adds this string to result, and removes these digits from digits.

  4. If there are exactly four digits left, it splits them into two groups of two digits each, joins each group into a string, and adds these strings to result.

  5. If there are less than four digits left (so there are two or three digits), it joins these digits into a string and adds this string to result.

  6. It joins the strings in result with dashes and returns this string.

The time complexity of this solution is O(n), where n is the length of number. The space complexity is also O(n), because it creates a list of digits and a list of groups of digits.