Skip to main content
Back to problems
#1694
Easy Algorithms

Reformat phone number

String
67.6% acceptance
Feb 25, 2026
398
206
You are given a phone number string. Remove all spaces and dashes, then group digits into blocks: blocks of 3 until 4 or fewer remain, then: 2 remaining: one block of 2. 3 remaining: one block of 3. 4 remaining: two blocks of 2 each. Join blocks with dashes.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn reformat_number(number: String) -> String {
    let digits: Vec<u8> = number.bytes().filter(|&b| b.is_ascii_digit()).collect();
    let mut blocks: Vec<String> = Vec::new();
    let mut i = 0;
    let n = digits.len();
    while i < n {
      let remaining = n - i;
      let take = if remaining > 4 {
        3
      } else if remaining == 4 {
        2
      } else {
        remaining
      };
      blocks.push(String::from_utf8(digits[i..i + take].to_vec()).unwrap());
      i += take;
    }
    blocks.join("-")
  }
}