858. Masking Personal Information
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
The problem requires us to mask personal information, which can be either an email address or a phone number. The first step is to differentiate between the two, and then apply the respective masking rules.
Solution
Masking Personal Information in Python
class Solution:
def maskPII(self, s: str) -> str:
# Check if the string contains '@', indicating an email.
if '@' in s:
# Email masking
s_lower = s.lower()
name, domain = s_lower.split('@')
# The masked name consists of the first letter, five asterisks, and the last letter.
masked_name = f"{name[0]}*****{name[-1]}"
return f"{masked_name}@{domain}"
else:
# Phone number masking
# Extract only the digits from the string.
digits = "".join(c for c in s if c.isdigit())
num_digits = len(digits)
# Get the last four digits of the phone number.
last_four = digits[-4:]
# Determine the length of the country code.
country_code_len = num_digits - 10
# Format based on the country code length.
if country_code_len == 0:
# No country code.
return f"***-***-{last_four}"
else:
# With country code.
prefix = f"+{ '*' * country_code_len }-"
return f"{prefix}***-***-{last_four}"
Masking Personal Information in Java
class Solution {
public String maskPII(String s) {
// Check if the string contains '@', which indicates it's an email.
int atIndex = s.indexOf('@');
if (atIndex != -1) { // It's an email
// Convert the entire string to lowercase.
s = s.toLowerCase();
// Extract the name part (before '@').
String name = s.substring(0, atIndex);
// The domain part starts from '@'.
String domain = s.substring(atIndex);
// The masked name is the first character, "*****", and the last character.
return name.charAt(0) + "*****" + name.charAt(name.length() - 1) + domain;
} else { // It's a phone number
// Extract all digits from the string using a regular expression.
String digits = s.replaceAll("[^0-9]", "");
// Get the last 4 digits.
String lastFour = digits.substring(digits.length() - 4);
int numDigits = digits.length();
// Format based on the total number of digits (which determines country code length).
if (numDigits == 10) {
return "***-***-" + lastFour;
} else {
// Build the country code prefix, e.g., +*-, +**-, +***-.
StringBuilder prefix = new StringBuilder("+");
for (int i = 0; i < numDigits - 10; i++) {
prefix.append('*');
}
prefix.append('-');
return prefix.toString() + "***-***-" + lastFour;
}
}
}
}
Masking Personal Information in C++
class Solution {
public:
string maskPII(string s) {
// Check if the string contains '@', which indicates it's an email.
size_t at_pos = s.find('@');
if (at_pos != string::npos) { // It's an email
// Convert the entire string to lowercase.
transform(s.begin(), s.end(), s.begin(), ::tolower);
// Extract the name part (before '@').
string name = s.substr(0, at_pos);
// The masked name is the first character, "*****", and the last character.
string masked_name = name.substr(0, 1) + "*****" + name.substr(name.length() - 1);
// The domain part starts from '@'.
string domain = s.substr(at_pos);
return masked_name + domain;
} else { // It's a phone number
string digits = "";
// Extract all digits from the string.
for (char c : s) {
if (isdigit(c)) {
digits += c;
}
}
// Get the last 4 digits.
string last_four = digits.substr(digits.length() - 4);
// Calculate the length of the country code.
int country_code_len = digits.length() - 10;\n
// Format based on country code length.
if (country_code_len == 0) {
return "***-***-" + last_four;
} else {
string prefix = "+" + string(country_code_len, '*') + "-";
return prefix + "***-***-" + last_four;
}
}
}
};
Masking Personal Information in TypeScript
function maskPII(s: string): string {
// Check if the string contains '@', indicating an email.
if (s.includes('@')) {
// Email masking
const lowerS = s.toLowerCase();
const atIndex = lowerS.indexOf('@');
const name = lowerS.substring(0, atIndex);
const domain = lowerS.substring(atIndex);
// The masked name is the first char, '*****', and the last char.
return `${name[0]}*****${name[name.length - 1]}${domain}`;
} else {
// Phone number masking
// Extract all digits using a regular expression.
const digits = s.replace(/\D/g, '');
const numDigits = digits.length;
// Get the last four digits.
const lastFour = digits.slice(-4);
// Determine the length of the country code.
const countryCodeLen = numDigits - 10;
// Format based on country code length.
if (countryCodeLen === 0) {
// No country code.
return `***-***-${lastFour}`;
} else {
// With country code.
const countryCodePrefix = `+${'*'.repeat(countryCodeLen)}-`;
return `${countryCodePrefix}***-***-${lastFour}`;
}
}
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.