algoadvance

Leetcode 831. Masking Personal Information

Problem Statement

You are given a string S which can be an email address or a phone number. Your task is to mask the personal information following these rules:

1. Email:

2. Phone Number:

Given the string S, you need to return the masked version of either the email or the phone number.

Clarifying Questions

  1. Can input string S be assumed to be well-formatted?
  2. Is it possible for the input string to be neither an email nor a phone number?
  3. Shall we expect valid email (not malformed)?
  4. Do phone numbers always have digits at the right positions (last 10 to 13 characters)?
  5. Are there any constraints on the character case for email?

Strategy

1. Recognize Email or Phone Number:

2. Masking the Email:

3. Masking the Phone Number:

4. Regex patterns and standard library methods will aid in recognizing and transforming the string accordingly.

Code

public class Solution {
    public String maskPII(String S) {
        if (S.contains("@")) {
            return maskEmail(S);
        } else {
            return maskPhone(S);
        }
    }

    private String maskEmail(String email) {
        email = email.toLowerCase();
        String[] parts = email.split("@");
        String namePart = parts[0];
        String domainPart = parts[1];
        return namePart.charAt(0) + "*****" + namePart.charAt(namePart.length() - 1) + "@" + domainPart;
    }

    private String maskPhone(String phone) {
        StringBuilder digits = new StringBuilder();
        for (char c : phone.toCharArray()) {
            if (Character.isDigit(c)) {
                digits.append(c);
            }
        }

        int len = digits.length();
        String localNumber = "***-***-" + digits.substring(len - 4);
        if (len == 10) {
            return localNumber;
        } else {
            StringBuilder maskedPhone = new StringBuilder("+");
            for (int i = 0; i < len - 10; i++) {
                maskedPhone.append('*');
            }
            maskedPhone.append('-').append(localNumber);
            return maskedPhone.toString();
        }
    }

    // Test the functionality
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.maskPII("LeetCode@LeetCode.com")); // Expected: "l*****e@leetcode.com"
        System.out.println(sol.maskPII("AB@qq.com"));             // Expected: "a*****b@qq.com"
        System.out.println(sol.maskPII("1(234)567-890"));          // Expected: "***-***-7890"
        System.out.println(sol.maskPII("+123-456-789-0123"));     // Expected: "+**-***-***-0123"
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI