Reformat Phone Number — LeetCode 1694 Python Solution

EasyString
Problem
#1694
Pattern
Hash Map
Reading time
2 min

The problem

You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.

Example

Input
number = "1-23-45 6"
Output
"123-456"
Explanation
The digits are "123456".

Python solution

Python
class Solution:
    def reformatNumber(self, number: str) -> str:
        number = number.replace("-", "").replace(" ", "")
        n = len(number)
        ans = [number[i * 3 : i * 3 + 3] for i in range(n // 3)]
        if n % 3 == 1:
            ans[-1] = ans[-1][:2]
            ans.append(number[-2:])
        elif n % 3 == 2:
            ans.append(number[-2:])
        return "-".join(ans)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1694. Reformat Phone Number is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1694. Reformat Phone Number?
LeetCode 1694. Reformat Phone Number is rated Easy on LeetCode.
What is the time complexity of LeetCode 1694. Reformat Phone Number?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1694. Reformat Phone Number?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1694. Reformat Phone Number cover?
LeetCode 1694. Reformat Phone Number is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview