Python 1694.py
class Solution:
def reformatNumber(self, number: str) -> str:
# clean up
number = number.replace(" ", "")
number = number.replace("-", "")
# groups of three
result = ""
while len(number) > 4:
result += number[: 3] + "-"
number = number[3 :]
if len(number) < 4:
# two or three digits
return result + number
else:
# twice two digits
return result + number[:2] + "-" + number[2:]
Difficulty
and has an acceptance rate of about 68% (70k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a single method reformatNumber that receives a telephone-number-like string containing digits, spaces, and hyphens. Its purpose is to return a new string where all non-digit separators are removed and the remaining digits are regrouped according to a specific rule: groups of three are emitted while possible, the final group is either two or three digits, and when exactly four digits remain they are split into two groups of two separated by a hyphen. The algorithm proceeds in three conceptual phases - cleaning, chunking, and final assembly - each reflected by a concise block of code.
Cleaning the Input
The first phase removes any characters that are not part of the numeric payload. Two successive replace calls eliminate spaces and hyphens, leaving a contiguous sequence of digits.
number = number.replace(" ", "")
number = number.replace("-", "")
By performing the replacements in place, the code avoids constructing intermediate collections such as lists or regular-expression matches. This contributes to a low-overhead transformation, especially for short to moderate input sizes.
Grouping Digits in Threes
After cleaning, the algorithm enters a loop that extracts groups of three digits while the remaining length exceeds four. Each iteration appends the three-digit slice followed by a hyphen to the accumulating result string, then discards the processed slice from the source.
result = ""
while len(number) > 4:
result += number[: 3] + "-"
number = number[3 :]
The loop condition len(number) > 4 guarantees that the final iteration leaves a tail of at most four characters, which is handled separately. Using slicing (number[: 3] and number[3 :]) provides direct access to the required substrings without auxiliary indexing structures. The incremental concatenation of result is performed only a few times, keeping the number of intermediate string objects modest.
Handling the Final Segment
When the loop terminates, the remaining number contains either two, three, or four digits. The code distinguishes these cases with a simple length check.
if len(number) < 4:
# two or three digits
return result + number
else:
# twice two digits
return result + number[:2] + "-" + number[2:]
If the tail length is less than four, it is appended directly to the previously built result. This covers the scenarios where the final group should be a single block of two or three digits. When exactly four digits remain, the code splits them into two groups of two, inserting a hyphen between them. This conditional logic ensures compliance with the required formatting rule without resorting to more complex branching.
Edge Cases Addressed
The implementation gracefully manages inputs that consist solely of separators; after cleaning, an empty string would cause the loop to be skipped and the final if branch to return an empty result, which aligns with the expectation that no digits produce an empty output.
Inputs whose length after cleaning is exactly two, three, or four are handled entirely by the final segment logic, avoiding any unnecessary loop iterations.
When the original string contains a mixture of spaces and hyphens interleaved with digits, the two replace calls strip all such characters regardless of their positions, ensuring that the grouping logic operates on a clean digit sequence.
Performance Optimizations Observed
The code relies on built-in string methods (replace, slicing, concatenation) that are implemented in C and thus execute efficiently. By avoiding conversion of the string into a list of characters, the algorithm reduces memory overhead and eliminates the need for explicit iteration over each character.
The while-loop processes the input in fixed-size chunks of three, which means the number of iterations is proportional to the length of the cleaned string divided by three. Each iteration performs a constant amount of work: a slice, a concatenation, and an assignment.
Because the result string is built incrementally with a small number of concatenations (one per three-digit group plus a final append), the overall number of temporary string objects remains low, minimizing the impact of Python’s immutable string semantics.
The final conditional avoids an extra pass over the data; it directly constructs the appropriate tail format in a single expression, thereby eliminating any need for additional loops or temporary buffers.
Overall, the design leverages Python’s efficient string handling primitives to achieve a compact and fast solution for the reformatting task.
ELI5 - Simplified Explanation
Imagine that a long string of numbers is like a messy pile of loose glitter on the floor. First, the code picks up all the extra spaces and little dashes that get in the way and puts them aside so only the plain numbers are left. Now that the numbers are in a neat row, the code starts making small groups. It takes the first three numbers, places them together, and adds a little hyphen after them to keep things tidy. It does this over and over again, grabbing three numbers at a time and adding a hyphen, until there are only four numbers left in the pile. When that happens, it stops making groups of three. If there are only two or three numbers left, it just sticks them onto the end of the line. If there are exactly four numbers left, it splits them into two pairs with a hyphen in the middle, because that way every little group stays easy to read.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1664: Ways to Make a Fair Array
- problem 1575: Count All Possible Routes
- problem 1665: Minimum Initial Energy to Finish Tasks
- problem 1691: Maximum Height by Stacking Cuboids
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality