Reformat Phone Number - Complete Solution Guide
Reformat Phone Number is LeetCode problem 1694, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given a phone number as a string number . number consists of digits, spaces ' ' , and/or dashes '-' . You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows: 2 digits: A single block of length 2. 3 digits: A single block of length 3. 4 digits: Two blocks of length 2 each. The blocks are then join
Detailed Explanation
The problem asks you to reformat a phone number string. The input string may contain spaces and hyphens along with digits. The goal is to remove all non-digit characters, then group the digits into blocks of three, with the last group being either two, three, or two blocks of two digits depending on the remaining number of digits. These blocks are then joined with hyphens. For example, "1-23-45 6" becomes "123-456", and "123 4-567" becomes "123-45-67".
Solution Approach
The provided solutions all follow a similar approach: first, they filter out non-digit characters. Then, they iterate through the digits, creating blocks of three until fewer than four digits remain. The remaining digits are handled based on the number of digits (2, 3, or 4). Finally, the blocks are joined using hyphens to form the reformatted number. This is done using iterative string manipulation.
Step-by-Step Algorithm
- Step 1: Extract only the digits from the input string. This involves iterating through the string and appending only digits to a new string or StringBuilder.
- Step 2: Initialize an empty result string or StringBuilder.
- Step 3: Iterate through the digits, creating blocks of 3 digits. Append each block to the result string, followed by a hyphen.
- Step 4: Handle the remaining digits (less than 4): If 4 digits remain, create two blocks of 2; if 3, one block of 3; if 2, one block of 2.
- Step 5: Append the last block(s) to the result string. Remove the trailing hyphen if it exists.
- Step 6: Return the reformatted number string.
Key Insights
- Insight 1: The core logic involves iterating through the digits and grouping them according to the specified rules. Handling the different cases for the remaining digits (2, 3, or 4) is crucial.
- Insight 2: String manipulation is key. Efficiently extracting digits, creating blocks, and joining them with hyphens are essential operations.
- Insight 3: Edge cases involve strings with fewer than 2 digits (which are invalid according to the constraints) or strings where the number of digits is a multiple of 3.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: String.
Companies
Asked at: Activision.