AI Engineer Problems › Guardrails

PII Masking & Sanitization Filter

Easy · Coding · Guardrails · Asked at Microsoft, Amazon

PII Masking & Sanitization Filter

Write a function mask_pii(text) that detects and replaces sensitive Personally Identifiable Information (PII) before sending prompts to external model APIs.

Your function must identify:

  1. Emails: Strings matching standard email formats.
  2. SSNs: Social Security Numbers in the format XXX-XX-XXXX.
  3. Phones: US Phone numbers in forms like (XXX) XXX-XXXX, XXX-XXX-XXXX, or XXX.XXX.XXXX.

Replace occurrences sequentially per type starting from 1 (e.g., [EMAIL_1], [EMAIL_2], [SSN_1], [PHONE_1]). Duplicate values of the same PII item must be replaced by the same placeholder.

Return a tuple (masked_text: str, mapping: Dict[str, str]) containing the scrubbed text and the dictionary mapping the placeholders back to their original values.

Example

text = "Contact Alice at alice@hospital.org or call 555-123-4567."
mask_pii(text)
# Returns: ("Contact Alice at [EMAIL_1] or call [PHONE_1].", {"[EMAIL_1]": "alice@hospital.org", "[PHONE_1]": "555-123-4567"})

Solve it in the browser on GenAIDojo