The problem statement in LeetCode is as follows:
You are given a phone number as a string number
. number
consists of digits, spaces ' '
, and/or dashes '-'
.
You want to reformat the phone number in a certain manner. Firstly, you should 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:
Finally, you reformat the digits into a string by joining the blocks with dashes.
Given a string number
, return the reformatted phone number.
2 <= number.length <= 100
number
consists of digits and the characters '-'
and ' '
.number
.def reformatNumber(number: str) -> str:
# Remove dashes and spaces
digits = ''.join(ch for ch in number if ch.isdigit())
result = []
i = 0
n = len(digits)
# Process the digits
while i < n:
if n - i > 4:
result.append(digits[i:i+3])
i += 3
else:
if n - i == 4:
result.append(digits[i:i+2])
result.append(digits[i+2:i+4])
else:
result.append(digits[i:])
break
return '-'.join(result)
# Example Usage
print(reformatNumber("1-23-45 6")) # Output: "123-456"
print(reformatNumber("123 4-567")) # Output: "123-45-67"
print(reformatNumber("123 4-5678")) # Output: "123-456-78"
The time complexity for this solution is (O(n)), where (n) is the length of the input string. This is because we pass through the string a couple of times: once to filter out non-digit characters and again to split the digits into groups.
The space complexity is also (O(n)) due to the storage requirements for the digit characters and the resulting blocks.
This ensures the solution is efficient and suitable for the input size constraints given in the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?