Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using core interview patterns strategy.
You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.
Email address:
An email address is:
'@' symbol, followed by'.' somewhere in the middle (not the first or last character).To mask an email:
"*****".Phone number:
A phone number is formatted as follows:
{'+', '-', '(', ')', ' '} separate the above digits in some way.To mask a phone number:
"***-***-XXXX" if the country code has 0 digits."+*-***-***-XXXX" if the country code has 1 digit."+**-***-***-XXXX" if the country code has 2 digits."+***-***-***-XXXX" if the country code has 3 digits."XXXX" is the last 4 digits of the local number.Example 1:
Input: s = "LeetCode@LeetCode.com" Output: "l*****e@leetcode.com" Explanation: s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.
Example 2:
Input: s = "AB@qq.com" Output: "a*****b@qq.com" Explanation: s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab" is 2 characters, it still must have 5 asterisks in the middle.
Example 3:
Input: s = "1(234)567-890" Output: "***-***-7890" Explanation: s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "***-***-7890".
Constraints:
s is either a valid email or a phone number.s is an email:
8 <= s.length <= 40s consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol.s is a phone number:
10 <= s.length <= 20s consists of digits, spaces, and the symbols '(', ')', '-', and '+'.Problem summary: You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules. Email address: An email address is: A name consisting of uppercase and lowercase English letters, followed by The '@' symbol, followed by The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character). To mask an email: The uppercase letters in the name and domain must be converted to lowercase letters. The middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks "*****". Phone number: A phone number is formatted as follows: The phone number contains 10-13 digits. The last 10 digits make up the local number. The remaining 0-3 digits, in the beginning, make up the country code. Separation characters from the
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"LeetCode@LeetCode.com"
"AB@qq.com"
"1(234)567-890"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #831: Masking Personal Information
class Solution {
public String maskPII(String s) {
if (Character.isLetter(s.charAt(0))) {
s = s.toLowerCase();
int i = s.indexOf('@');
return s.substring(0, 1) + "*****" + s.substring(i - 1);
}
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
}
}
s = sb.toString();
int cnt = s.length() - 10;
String suf = "***-***-" + s.substring(s.length() - 4);
return cnt == 0 ? suf
: "+"
+ "*".repeat(cnt) + "-" + suf;
}
}
// Accepted solution for LeetCode #831: Masking Personal Information
func maskPII(s string) string {
i := strings.Index(s, "@")
if i != -1 {
s = strings.ToLower(s)
return s[0:1] + "*****" + s[i-1:]
}
t := []rune{}
for _, c := range s {
if c >= '0' && c <= '9' {
t = append(t, c)
}
}
s = string(t)
cnt := len(s) - 10
suf := "***-***-" + s[len(s)-4:]
if cnt == 0 {
return suf
}
return "+" + strings.Repeat("*", cnt) + "-" + suf
}
# Accepted solution for LeetCode #831: Masking Personal Information
class Solution:
def maskPII(self, s: str) -> str:
if s[0].isalpha():
s = s.lower()
return s[0] + '*****' + s[s.find('@') - 1 :]
s = ''.join(c for c in s if c.isdigit())
cnt = len(s) - 10
suf = '***-***-' + s[-4:]
return suf if cnt == 0 else f'+{"*" * cnt}-{suf}'
// Accepted solution for LeetCode #831: Masking Personal Information
struct Solution;
impl Solution {
fn mask_pii(s: String) -> String {
if let Some(i) = s.find('@') {
let s = s.to_lowercase();
format!("{}*****{}", &s[0..1], &s[i - 1..])
} else {
let digits: String = s.chars().filter(|&c| ('0'..='9').contains(&c)).collect();
let n = digits.len();
match digits.len() {
13 => format!("+***-***-***-{}", &digits[n - 4..]),
12 => format!("+**-***-***-{}", &digits[n - 4..]),
11 => format!("+*-***-***-{}", &digits[n - 4..]),
_ => format!("***-***-{}", &digits[n - 4..]),
}
}
}
}
#[test]
fn test() {
let s = "LeetCode@LeetCode.com".to_string();
let res = "l*****e@leetcode.com".to_string();
assert_eq!(Solution::mask_pii(s), res);
let s = "AB@qq.com".to_string();
let res = "a*****b@qq.com".to_string();
assert_eq!(Solution::mask_pii(s), res);
let s = "1(234)567-890".to_string();
let res = "***-***-7890".to_string();
assert_eq!(Solution::mask_pii(s), res);
let s = "86-(10)12345678".to_string();
let res = "+**-***-***-5678".to_string();
assert_eq!(Solution::mask_pii(s), res);
}
// Accepted solution for LeetCode #831: Masking Personal Information
function maskPII(s: string): string {
const i = s.indexOf('@');
if (i !== -1) {
let ans = s[0].toLowerCase() + '*****';
for (let j = i - 1; j < s.length; ++j) {
ans += s.charAt(j).toLowerCase();
}
return ans;
}
let t = '';
for (const c of s) {
if (/\d/.test(c)) {
t += c;
}
}
const cnt = t.length - 10;
const suf = `***-***-${t.substring(t.length - 4)}`;
return cnt === 0 ? suf : `+${'*'.repeat(cnt)}-${suf}`;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.