Python 0831.py
class Solution:
def maskPII(self, s: str) -> str:
if s.count("@") > 0:
# mail
s = s.lower()
a, b = s.split("@")
return a[0] + "*****" + a[-1] + "@" + b
# phone
prefix = { 10: "", 11: "+*-", 12: "+**-", 13: "+***-" }
digits = [ c for c in s if "0" <= c <= "9" ]
last = "".join(digits[-4 : ])
return prefix[len(digits)] + "***-***-" + last
Difficulty
and has an acceptance rate of about 56% (70k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The maskPII method receives a string that represents either an email address or a telephone number and returns a version where personally identifying information is concealed. The function first determines the type of input by checking for the presence of the '@' character. Depending on the result, it follows a distinct processing path for email addresses or phone numbers, applying specific masking rules to each.
Email handling
When the input contains at least one '@', the routine treats it as an email address. The string is converted to lower-case to ensure a uniform output regardless of the original case. It is then split into the local part and the domain part at the '@' delimiter. The masked email is assembled by keeping the first and last characters of the local part, inserting five asterisks in between, and re-attaching the unchanged domain.
if s.count("@") > 0:
s = s.lower()
a, b = s.split("@")
return a[0] + "*****" + a[-1] + "@" + b
The code gracefully handles email addresses that contain uppercase letters, mixed case domains, or additional '@' symbols beyond the first one, because the count check only requires at least one occurrence and the split operation separates at the first '@'. The masking pattern always produces a five-character asterisk block, regardless of the length of the original local part, as long as the local part has at least two characters (the first and last are accessed directly).
Phone handling
If the input does not contain '@', the function assumes it is a telephone number. All characters that are not digits are filtered out using a list comprehension, producing a list of numeric characters only. The length of this digit list determines the appropriate international prefix, which is retrieved from a predefined dictionary. The last four digits of the number are kept visible, while the preceding digits are replaced by three groups of three asterisks separated by hyphens. The final masked phone string concatenates the selected prefix, the fixed "***-***-" segment, and the extracted last four digits.
prefix = { 10: "", 11: "+*-", 12: "+**-", 13: "+***-" }
digits = [c for c in s if "0" <= c <= "9"]
last = "".join(digits[-4:])
return prefix[len(digits)] + "***-***-" + last
This approach correctly processes phone numbers that may include spaces, hyphens, parentheses, or plus signs, because any non-digit character is ignored during digit extraction. It also accommodates numbers with 10 to 13 digits, covering typical domestic formats as well as international numbers with up to three additional country-code digits. The prefix dictionary maps each possible digit count to the required masking prefix, ensuring that the output reflects the correct number of concealed country-code symbols.
Edge case handling
The email branch tolerates inputs where the local part is exactly two characters long; the first and last characters are still distinct, and the five asterisks are inserted between them. If the local part were shorter than two characters, the indexing would still succeed because Python allows negative indexing, but the typical problem constraints guarantee a minimum length, so the code operates safely within those bounds.
In the phone branch, the digit extraction step guarantees that any formatting characters are removed, so inputs such as "+1 (234) 567-8901" or "123-456-7890" are treated identically after filtering. The slice digits[-4:] safely returns the final four digits even when the total number of digits is exactly four, though the problem specification expects at least ten digits; the prefix lookup will still provide an appropriate empty or prefixed string based on the digit count.
Performance considerations
The function processes the input string in a single pass when extracting digits for phone numbers, using a list comprehension that evaluates each character only once. The subsequent join operation concatenates the last four digits, which is efficient because it works on a small, fixed-size slice. For email handling, converting the entire string to lower case and splitting at the first '@' are linear operations relative to the input length. The dictionary lookup for the phone prefix is a constant-time operation, and the final string concatenations are performed with a small, fixed number of components, minimizing overhead. Overall, the implementation avoids nested loops or repeated scans, leading to a streamlined execution path for both email and phone inputs.
ELI5 - Simplified Explanation
Imagine you have a secret box that needs to keep private information safe. This code is like a magical filter that takes a long piece of text and hides parts of it so that prying eyes cannot see the whole thing.
When the code looks at an email address, it first makes all the letters tiny. Then it captures the very first letter and the very last letter of the name part. It puts five little stars in the middle, just like a secret code, and then sticks the rest of the address back on exactly as it was.
When the code looks at a phone number, it first hunts for all the numbers and pretends the extra symbols like dashes or dots are not there. It keeps the last four digits so people know who it belongs to, but it replaces all the earlier numbers with stars and clever little patterns depending on how long the original phone number was. Every piece of private information that goes into this filter comes out looking much more mysterious and safe.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| Krazune | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| Krazune | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 462: Minimum Moves to Equal Array Elements II
- problem 468: Validate IP Address
- problem 874: Walking Robot Simulation
- problem 886: Possible Bipartition
- problem 1754: Largest Merge Of Two Strings
- problem 2055: Plates Between Candles
- problem 2086: Minimum Number of Food Buckets to Feed the Hamsters
- problem 2105: Watering Plants II
- problem 2816: Double a Number Represented as a Linked List
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality