#831

Masking Personal Information

Medium
String
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach involves checking if the input string is an email or a phone number. For emails, we will mask the middle characters and convert letters to lowercase. For phone numbers, we will remove special characters and format them accordingly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the string contains '@'. If it does, treat it as an email; otherwise, treat it as a phone number.
  2. 2Step 2: For an email, convert all letters to lowercase, replace the middle characters of the name with '*****', and return the masked email.
  3. 3Step 3: For a phone number, remove all non-digit characters, extract the country code and local number, and format it according to the rules.
solution.py19 lines
1# Full working Python code
2import re
3
4def mask_personal_info(s):
5    if '@' in s:
6        # Mask email
7        name, domain = s.split('@')
8        name = name[0] + '*****' + name[-1]
9        return (name.lower() + '@' + domain.lower())
10    else:
11        # Mask phone number
12        digits = re.sub(r'[^0-9]', '', s)
13        country_code = len(digits) - 10
14        local_number = digits[-10:]
15        masked_number = '***-***-' + local_number[-4:]
16        if country_code > 0:
17            masked_number = '+' + '*' * country_code + '-' + masked_number
18        return masked_number
19

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.