Problem 1694

Abstract / Summary

Given a phone number string with digits and possibly other characters rearrange and format it into groups of three digits separated by hyphens with groups of two or four digits where needed.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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:]
18 lines | 538 bytes | submitted January 18, 2024 | GitHub   33% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (70k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.33 | σ = 0.61

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
30 links | 18 authors | 10 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 18, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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