Leetcode 1694: Reformat Phone Number

grid47
grid47
Exploring patterns and algorithms
May 21, 2024 6 min read

You are given a phone number as a string. The string consists of digits, spaces, and/or dashes. Your task is to reformat the phone number by removing spaces and dashes, then grouping the digits into blocks of length 3 until there are at most 4 digits left. Afterward, follow specific grouping rules for the remaining digits and join the blocks with dashes.
Problem
Approach
Steps
Complexity
Input: The input consists of a string 'number', which contains digits, spaces, and dashes.
Example: "9-87-65 4"
Constraints:
• 2 <= number.length <= 100
• number contains digits and the characters '-' and ' '.
• There are at least two digits in number.
Output: The output is a string representing the reformatted phone number with digits grouped and separated by dashes as per the specified rules.
Example: "987-654"
Constraints:
• The output string should have no blocks of length 1 and at most two blocks of length 2.
Goal: The goal is to reformat the phone number optimally by grouping digits as described in the problem statement.
Steps:
• Remove spaces and dashes from the input string.
• Group the digits into blocks of length 3 while more than 4 digits remain.
• For the remaining digits, apply the appropriate grouping rule.
• Join the blocks using dashes and return the result.
Goal: Constraints related to the input and output formatting.
Steps:
• The input will always have at least two digits.
• The length of the input will be between 2 and 100 characters.
Assumptions:
• The phone number will contain only digits, spaces, and dashes.
• The phone number will contain at least two digits.
Input: "9-87-65 4"
Explanation: After removing spaces and dashes, the digits are "987654". These are grouped into two blocks: "987" and "654". The final output is "987-654".

Input: "3 1-2 45"
Explanation: After removing spaces and dashes, the digits are "31245". These are grouped into blocks: "312" and "45". The final output is "312-45".

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus