Reformat Phone Number

Easy
1185.

Reformat Phone Number

Reformat Phone Number is an easy coding problem on strings and simulation, asked in Amazon and Google interviews.

A phone number number is given as a string of digits, spaces ' ' and dashes '-'.

Reformat it as follows. First drop every space and dash. Then cut the digits, from left to right, into blocks of 3 until 4 or fewer digits remain, and finish with:

  • 2 remaining digits → one block of 2;
  • 3 remaining digits → one block of 3;
  • 4 remaining digits → two blocks of 2.

Join the blocks with dashes and return the result. No block of length 1 is ever produced, and at most two blocks have length 2.

Example 1

Input
number = "98 76-5 4"
Output
"987-654"

Example 2

Input
number = "1-2 3-4"
Output
"12-34"
Explanation
Four digits become two blocks of two.

Example 3

Input
number = "4 0 0-1 2 3 4 5"
Output
"400-123-45"

Constraints

  • 2 <= number.length <= 100
  • number consists of digits and the characters '-' and ' '
  • there are at least two digits in number
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} number
 * @return {string}
 */
var reformatNumber = function(number) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Reformat Phone Number — Solution in Python, Java & C++

Reformat Phone Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.

Reformat Phone Number is an easy coding problem on strings and simulation, asked in Amazon and Google interviews.

  • Difficulty: Easy
  • Topics: Strings, Simulation
  • Asked at: Amazon, Google
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

A phone number number is given as a string of digits, spaces ' ' and dashes '-'.

Reformat it as follows. First drop every space and dash. Then cut the digits, from left to right, into blocks of 3 until 4 or fewer digits remain, and finish with:

  • 2 remaining digits → one block of 2;
  • 3 remaining digits → one block of 3;
  • 4 remaining digits → two blocks of 2.

Join the blocks with dashes and return the result. No block of length 1 is ever produced, and at most two blocks have length 2.

Example 1

Input: number = "98 76-5 4"
Output: "987-654"

Example 2

Input: number = "1-2 3-4"
Output: "12-34"
Explanation: Four digits become two blocks of two.

Example 3

Input: number = "4 0 0-1 2 3 4 5"
Output: "400-123-45"

Constraints

  • 2 <= number.length <= 100
  • number consists of digits and the characters '-' and ' '
  • there are at least two digits in number

Hints for Reformat Phone Number

  1. Hint 1

    Strip the spaces and dashes first; only the digit string matters.

  2. Hint 2

    Take blocks of three while more than four digits remain.

  3. Hint 3

    Four leftover digits split as 2 + 2; two or three leftover digits form the last block on their own.

How to solve Reformat Phone Number

After removing separators the rule is a simple loop: greedily emit blocks of three while more than four digits are left, then handle the 2/3/4 tail specially so no block of one is ever created.

Approach

  1. Build d, the string of digits in order.
  2. Set i = 0; while len(d) - i > 4, emit d[i..i+3) and advance i by 3.
  3. If exactly 4 digits remain, emit d[i..i+2) and d[i+2..i+4); otherwise emit the remaining 2 or 3 digits as one block.
  4. Join the blocks with -.

Why it works

Taking 3 while more than 4 remain always leaves 2, 3 or 4 digits (a count above 4 minus 3 is at least 2), and those three tails are exactly the cases the statement defines. The procedure mirrors the statement step by step, so the result is unique and correct.

Complexity

  • Time — O(n)
  • Space — O(n)

Pitfalls

  • Stopping when fewer than 3 digits remain would leave a block of 1 for lengths like 4 or 7.
  • Separators can appear anywhere, including several in a row or at the ends.
  • Do not put a dash after the final block.

Reference solution

Python

def reformatNumber(number: str) -> str:
    d = ''.join(c for c in number if c.isdigit())
    blocks = []
    i = 0
    while len(d) - i > 4:
        blocks.append(d[i:i + 3])
        i += 3
    if len(d) - i == 4:
        blocks.append(d[i:i + 2])
        blocks.append(d[i + 2:])
    else:
        blocks.append(d[i:])
    return '-'.join(blocks)

Java

public static String reformatNumber(String number) {
    StringBuilder d = new StringBuilder();
    for (int k = 0; k < number.length(); k++) {
        char c = number.charAt(k);
        if (c >= '0' && c <= '9') d.append(c);
    }
    int n = d.length(), i = 0;
    StringBuilder res = new StringBuilder();
    while (n - i > 4) {
        res.append(d, i, i + 3).append('-');
        i += 3;
    }
    if (n - i == 4) res.append(d, i, i + 2).append('-').append(d, i + 2, n);
    else res.append(d, i, n);
    return res.toString();
}

C++

string reformatNumber(string number) {
    string d;
    for (char c : number) if (c >= '0' && c <= '9') d += c;
    int n = d.size(), i = 0;
    string res;
    while (n - i > 4) {
        res += d.substr(i, 3) + "-";
        i += 3;
    }
    if (n - i == 4) res += d.substr(i, 2) + "-" + d.substr(i + 2, 2);
    else res += d.substr(i);
    return res;
}

JavaScript

var reformatNumber = function(number) {
    var d = "";
    for (var k = 0; k < number.length; k++) {
        var c = number[k];
        if (c >= "0" && c <= "9") d += c;
    }
    var blocks = [];
    var i = 0;
    while (d.length - i > 4) {
        blocks.push(d.substring(i, i + 3));
        i += 3;
    }
    if (d.length - i === 4) {
        blocks.push(d.substring(i, i + 2));
        blocks.push(d.substring(i + 2));
    } else {
        blocks.push(d.substring(i));
    }
    return blocks.join("-");
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 515 strings problems · the whole catalogue

Learn the technique: Strings