Skip to main content

Masking Personal Information - Solution & Explanation

MediumString11 min readAsked at: Salesforce, Google, Twitter
Practice this problem

Problem Statement

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 set {'+', '-', '(', ')', ' '} separate the above digits in some way.

To mask a phone number:

  • Remove all separation characters.
  • The masked phone number should have the form:
    • "***-***-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.
  • If s is an email:
    • 8 <= s.length <= 40
    • s consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol.
  • If s is a phone number:
    • 10 <= s.length <= 20
    • s consists of digits, spaces, and the symbols '(', ')', '-', and '+'.

Approach Overview

Problem Overview: You receive a string that represents either an email address or a phone number. The task is to mask sensitive parts of the string while preserving a few characters so the result still identifies the contact. Email masking keeps the first and last character of the name while replacing the middle with asterisks. Phone masking hides all digits except the last four and formats the result depending on whether a country code exists.

Approach 1: Email and Phone Number Detection and Masking (O(n) time, O(n) space)

The input type determines the masking rule. Scan the string once to check for the '@' character. If it exists, treat the input as an email; otherwise treat it as a phone number. For emails, convert everything to lowercase, keep the first and last character of the local name, and insert five asterisks between them before appending the domain. For phone numbers, iterate through the string and extract only digits, ignoring characters like '(', ')', '+', spaces, or dashes. Keep the last four digits visible and replace the rest with *. If more than ten digits exist, prepend the correct country code mask using +***- style formatting. This approach relies purely on string manipulation and a single pass through the input.

The key insight is separating detection from transformation. Once you know the input type, the masking rule becomes deterministic. You perform simple operations such as substring extraction, digit filtering, and concatenation. Time complexity is O(n) because each character is processed at most once, and space complexity is O(n) for constructing the masked output.

Approach 2: Regular Expression for Detecting Number of Digits (O(n) time, O(n) space)

This variation uses regular expressions to simplify parsing. Instead of manually iterating to filter digits, apply a regex pattern like \d to extract all digits from the input. The resulting list directly reveals how many digits the phone number contains, which determines the country code length. For emails, a simple split around '@' combined with lowercase conversion produces the masked format quickly.

Regex makes the implementation shorter and easier to read in languages that support strong pattern libraries. Digit extraction and counting happen in one step, avoiding manual conditional checks. Complexity remains O(n) time because the regex engine scans the string once, and O(n) space for storing extracted characters.

Recommended for interviews: The direct detection and masking approach is what interviewers usually expect. It shows that you can handle conditional parsing, apply exact formatting rules, and reason through edge cases such as international phone numbers. Regex solutions are concise and elegant but sometimes hide the logic interviewers want to see. Demonstrating the explicit string processing steps proves you understand how the masking rules are implemented.

Approach 1: Email and Phone Number Detection and Masking

This approach involves first detecting whether the input is an email address or a phone number. For emails, the middle characters of the name part should be replaced with asterisks, and then both the name and domain should be converted to lowercase. For phone numbers, we remove non-numeric characters and replace the digits with the correct masking format based on the length.

The function first checks if the input has an '@' character. If it does, it's considered an email and is split into name and domain parts. The name is then masked with asterisks by using the first and last letter with '*****' in between, combined with the lowercase domain.

For phone numbers, all digits are extracted, and the function constructs the masked version based on the number of digits using string concatenations.

Code

Python

JavaScript

Complexity

Time complexity is O(n), where n is the length of the input string. Space complexity is O(1) as we are not using extra space relative to input size beyond required variables.

Try this approach in the editor →

Approach 2: Regular Expression for Detecting Number of Digits

In this approach, we utilize regular expressions to identify phone numbers by counting the digits in the input. Once identified, we process and mask the input accordingly. For email, the masking continues as described previously.

This C++ solution first checks whether the input contains '@'. If yes, it treats it as an email, converts everything to lowercase, and masks the name part. Otherwise, it processes the input string to extract digits using loops and constructs the masked phone number accordingly.

Code

C++

C

Complexity

Time complexity is O(n), the complexity is driven by the initial parsing of the string. Space complexity is O(n) due to storage of the digits string.

Try this approach in the editor →

Approach 3: Simulation

According to the problem description, we can first determine whether the string s is an email or a phone number, and then handle it accordingly.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the string s.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Email and Phone Number Detection and Masking

Time complexity is O(n), where n is the length of the input string. Space complexity is O(1) as we are not using extra space relative to input size beyond required variables.

Regular Expression for Detecting Number of Digits

Time complexity is O(n), the complexity is driven by the initial parsing of the string. Space complexity is O(n) due to storage of the digits string.

Simulation

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Email and Phone Detection with Manual ParsingO(n)O(n)Best for interviews and most implementations where explicit string processing is expected
Regex-Based Digit ExtractionO(n)O(n)Useful when regex libraries are available and concise parsing is preferred

Video Solution

LeetCode 831. Masking Personal Information Solution Explained - JavaAlgorithms and Data Structures Course294 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Masking Personal Information easy or hard?
Masking Personal Information is considered a Medium difficulty problem on LeetCode. The algorithm itself is straightforward, but the challenge comes from implementing exact formatting rules and handling edge cases like international phone numbers.
Masking Personal Information Python/Java solution
In Python or Java, the common approach checks for '@' to detect emails and uses string operations to construct the masked result. Phone numbers are processed by extracting digits and formatting them with '*' and hyphens. Both implementations follow the same O(n) time logic.
How to solve Masking Personal Information in O(n)?
Process the string in a single pass. If '@' exists, convert the email to lowercase, keep the first and last character of the name, and replace the middle with five asterisks. If it is a phone number, extract all digits, keep the last four visible, and replace the rest with '*' while formatting the country code. Every character is handled once, giving O(n) complexity.
What is the best approach for Masking Personal Information?
The best approach is detecting whether the input is an email or phone number and then applying the corresponding masking rule using string parsing. Scan the string for '@' to identify emails, otherwise extract digits for phone numbers. This solution runs in O(n) time and uses O(n) space to build the masked result.
Is Masking Personal Information asked at Google/Amazon/Meta?
String parsing and formatting problems like Masking Personal Information frequently appear in interviews at companies such as Amazon, Google, and Meta. They test attention to detail, edge‑case handling, and the ability to implement precise formatting rules.
What data structure is used in Masking Personal Information?
The problem primarily uses string manipulation and simple character arrays or lists. For phone numbers, a temporary list of digits is often used after filtering the input string. No advanced data structures are required.
What is the time complexity of Masking Personal Information?
The optimal solution runs in O(n) time where n is the length of the input string. Each character is scanned once to detect the type and filter digits if needed. Space complexity is O(n) because a new masked string is constructed.

Ready to solve this problem?

Practice Masking Personal Information with our built-in code editor and test cases.

Practice on FleetCode