Masking Personal Information
Problem
Mask a string s that is either an email (lowercase the address, keep first and last name letter with '*****' middle, keep domain) or a phone number (keep last 4 digits, mask the rest, add country code prefix).
s = "[email protected]""l*****[email protected]"def maskPII(s):
if "@" in s:
name, domain = s.lower().split("@")
return name[0] + "*****" + name[-1] + "@" + domain
digits = "".join(c for c in s if c.isdigit())
local = "***-***-" + digits[-4:]
extra = len(digits) - 10
if extra == 0: return local
return "+" + "*" * extra + "-" + local
function maskPII(s) {
if (s.includes("@")) {
const [name, domain] = s.toLowerCase().split("@");
return name[0] + "*****" + name[name.length - 1] + "@" + domain;
}
const digits = s.replace(/\D/g, "");
const local = "***-***-" + digits.slice(-4);
const extra = digits.length - 10;
if (extra === 0) return local;
return "+" + "*".repeat(extra) + "-" + local;
}
class Solution {
public String maskPII(String s) {
int at = s.indexOf('@');
if (at >= 0) {
String lower = s.toLowerCase();
return lower.charAt(0) + "*****" + lower.charAt(at - 1) + lower.substring(at);
}
StringBuilder digits = new StringBuilder();
for (char c : s.toCharArray()) if (Character.isDigit(c)) digits.append(c);
String d = digits.toString();
String local = "***-***-" + d.substring(d.length() - 4);
int extra = d.length() - 10;
if (extra == 0) return local;
return "+" + "*".repeat(extra) + "-" + local;
}
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string maskPII(string s) {
size_t at = s.find('@');
if (at != string::npos) {
for (auto &c : s) c = tolower(c);
return string(1, s[0]) + "*****" + s[at - 1] + s.substr(at);
}
string digits;
for (char c : s) if (isdigit(c)) digits += c;
string local = "***-***-" + digits.substr(digits.size() - 4);
int extra = digits.size() - 10;
if (extra == 0) return local;
return "+" + string(extra, '*') + "-" + local;
}
};
Explanation
This is a rules problem, not a clever-algorithm problem. The input is either an email or a phone number, and we just apply the exact masking format each one requires.
We tell them apart by looking for an @. If it is there, it is an email: lowercase the whole thing, split on @ into name and domain, then keep only the first and last letter of the name with "*****" in between, and re-attach the domain.
If there is no @, it is a phone number. We pull out just the digits, then keep the last 4 and mask the rest as "***-***-" followed by those four digits.
A phone number may include an international code. We compute extra = len(digits) - 10; if there are exactly 10 digits there is no country code, so we return the local format. Otherwise we prepend a +, a run of * matching the country-code length, and a dash.
Example: "[email protected]" has an @, so it lowercases to "[email protected]" and masks the name to "l*****e", giving "l*****[email protected]".