#1694

Reformat Phone Number

Easy
StringString ManipulationGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach efficiently processes the digits in a single pass, grouping them according to the rules without unnecessary string operations. This method minimizes time complexity by using a list to collect blocks before joining them at the end.

⚙️

Algorithm

5 steps
  1. 1Step 1: Remove all spaces and dashes from the input string.
  2. 2Step 2: Initialize an empty list to hold the blocks of digits.
  3. 3Step 3: Use a while loop to process the digits, grouping them into blocks of 3 until 4 or fewer digits remain.
  4. 4Step 4: Handle the last 4 digits according to the specified rules and append them to the list.
  5. 5Step 5: Join the blocks with dashes and return the formatted string.
solution.py13 lines
1def reformatNumber(number):
2    digits = ''.join(c for c in number if c.isdigit())
3    blocks = []
4    i = 0
5    while len(digits) - i > 4:
6        blocks.append(digits[i:i+3])
7        i += 3
8    if len(digits) - i == 4:
9        blocks.append(digits[i:i+2])
10        blocks.append(digits[i+2:i+4])
11    else:
12        blocks.append(digits[i:])
13    return '-'.join(blocks)

Complexity note: The complexity is O(n) because we traverse the string once to clean it and again to group the digits, making it efficient for larger inputs.

  • 1Removing non-digit characters is crucial for processing.
  • 2Understanding the grouping rules helps in implementing the logic correctly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.