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:


This solution works as follows:
It creates a list of digits by iterating over the characters in
number
and keeping only the digits.It creates an empty list
result
to hold the groups of digits.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 fromdigits
.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
.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
.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.