Tiered Identity Validation for Business Onboarding
StringsAuto-graded · 20 test casesLast updated
Tests your ability to implement a sequential rule-engine with string normalization, token-set comparison, and strict short-circuit logic across three validation tiers.
Problem
A financial platform needs to validate businesses before granting them access to payment features. Validation works in three progressive tiers. A business must clear each tier before the next one is evaluated. Your job is to determine the highest tier a submission reaches.
Implement check_business_identity(submitted: dict, registry: dict) -> int, which returns 0, 1, 2, or 3 — the highest tier passed.
Tier 1 — Format Check
Return 1 if all three conditions below hold; otherwise return 0.
submitted["legal_name"]must be a string with at least one non-whitespace character.submitted["country"]must be a string of exactly two ASCII letters (case-insensitive).submitted["tax_id"]must be a string that, after stripping all hyphens (-) and spaces, contains only alphanumeric characters and has a length between 8 and 10 inclusive.
Tier 2 — Registry Match
Requires Tier 1. Return 2 if all three conditions below hold; otherwise return 1.
submitted["country"]matchesregistry["country"]case-insensitively.submitted["tax_id"]matchesregistry["tax_id"]after stripping hyphens and spaces from both sides and uppercasing.- The business name tokens of
submitted["legal_name"]andregistry["legal_name"]are identical, where business name tokens are computed as follows:- Lowercase the string.
- Remove every character that is not an ASCII letter, digit, or whitespace.
- Split on whitespace into tokens.
- Discard any token that belongs to the set
{"inc", "llc", "corp", "corporation", "ltd", "co", "company"}. - Both sides must produce at least one token, and those token sets must be equal.
Tier 3 — Ownership Match
Requires Tier 2. Return 3 if both conditions below hold; otherwise return 2.
submitted.get("owners", [])is a non-empty list.- Every name in
submitted["owners"]has a match somewhere inregistry.get("owners", []). Two names match when, after lowercasing and removing every character that is not alphanumeric or whitespace, their sets of whitespace-delimited tokens are identical (so"Jane Doe"and"Doe, Jane"match).
Constraints
- Both
submittedandregistryare plain dicts; any key may be absent or hold an unexpected type — handle gracefully without raising. - Country codes contain only printable characters; no guarantee they are valid ISO codes.
- Tax ID strings may contain hyphens, spaces, letters, and digits; other characters are possible.
- Owner lists, when present, contain strings; the registry may have more owners than the submission.
- Name comparison uses sets of tokens, so word order is irrelevant.
- A legal name whose tokens are entirely suffixes (e.g.,
"Inc. LLC") must fail Tier 2. 1 ≤ len(submitted["legal_name"]) ≤ 200when the key is present and a string.1 ≤ len(owners) ≤ 50per side when the key is present and a list.
Examples
Example 1
Input: check_business_identity({'legal_name': 'Acme Payments, Inc.', 'country': 'us', 'tax_id': '12-345678', 'owners': ['Jane Doe', 'Bob Smith']}, {'legal_name': 'ACME PAYMENTS LLC', 'country': 'US', 'tax_id': '12345678', 'owners': ['Doe, Jane', 'Smith Bob', 'Alice Brown']})
Output: 3
Example 2
Input: check_business_identity({'legal_name': 'Global Freight Ltd', 'country': 'CA', 'tax_id': 'AB-998877', 'owners': []}, {'legal_name': 'Global Freight Company', 'country': 'CA', 'tax_id': 'AB998877', 'owners': ['Carol Danvers']})
Output: 2
Hints
Hint 1
Break the problem into three small, independently testable helpers — one per tier — and short-circuit: if tier N fails, return N-1 immediately without evaluating later tiers.
Hint 2
For legal name comparison, the tricky edge case is a name that consists entirely of legal suffixes like 'Inc.' or 'Co.' — after stripping suffixes the token set is empty, and an empty set should never match anything.
Hint 3
Normalise the tax ID (strip hyphens and spaces, then uppercase) on both the submitted and registry sides before comparing, so differences in formatting don't cause false negatives.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that this is a short-circuiting pipeline, not a scoring system. Each tier is independent of the next, so the cleanest structure is:
if tier 1 fails → return 0
if tier 2 fails → return 1
if tier 3 fails → return 2
return 3
Most of the work is string normalization. Writing small, named helpers keeps each tier readable and independently testable.
Tier 1
Three separate guards, each failing fast:
legal_name: type check then.strip()to catch all-whitespace strings.country:re.fullmatch(r"[A-Za-z]{2}", ...)is the right tool here.str.isalpha()would accept Unicode letters like"Ü", which the spec does not allow.tax_id: strip hyphens and spaces first, then checkisalnum()andisascii()together with the length bounds. Usingisascii()on top ofisalnum()is a clean way to exclude non-ASCII alphanumerics in a single step.
Tier 2
Three comparisons, all case-normalised:
- Country:
.upper()on both sides. - Tax ID: strip formatting from both sides, then uppercase before comparing. This handles registries that store IDs with or without hyphens.
- Legal name: compute business name token sets — lowercase, remove non-alphanumeric/non-whitespace characters, split, subtract the suffix vocabulary, compare sets. The mandatory non-empty check prevents
"Inc."from matching"LLC", since both would otherwise reduce to an empty set.
Tier 3
Pre-build a list of token sets from the registry's owner list, then check that every submitted owner's token set appears in it. Order within a name does not matter because we compare sets, which is why "Jane Doe" and "Doe, Jane" are treated as equal. Extra registry owners are fine; only submitted owners must be covered.
Why it is correct
- Defensive type checks at every boundary mean malformed or missing keys return the appropriate lower tier instead of raising an exception.
- Set comparison for names makes the logic order-independent without any sorting.
- The empty-token-set guard after suffix removal closes the hole where two pure-suffix names would spuriously match.
Complexity
Let L be the total number of characters across all input strings.
- Time: O(L) — each string is scanned a constant number of times; set operations are linear in token count.
- Space: O(L) — for the token sets, dominated by the registry owner index.
Reference Solution
import re
from typing import Dict
_LEGAL_SUFFIXES = {"inc", "llc", "corp", "corporation", "ltd", "co", "company"}
_COUNTRY_PATTERN = re.compile(r"[A-Za-z]{2}")
_ALNUM_ONLY = re.compile(r"[^a-z0-9\s]")
def _strip_tax_id(value: str) -> str:
return value.replace("-", "").replace(" ", "")
def _name_tokens(value: str, drop_suffixes: bool = False) -> set:
if not isinstance(value, str):
return set()
cleaned = _ALNUM_ONLY.sub("", value.lower())
tokens = cleaned.split()
if drop_suffixes:
tokens = [t for t in tokens if t not in _LEGAL_SUFFIXES]
return set(tokens)
def check_business_identity(submitted: Dict, registry: Dict) -> int:
# --- Tier 1: format validation ---
if not isinstance(submitted, dict) or not isinstance(registry, dict):
return 0
legal_name = submitted.get("legal_name")
country = submitted.get("country")
tax_id = submitted.get("tax_id")
if not isinstance(legal_name, str) or not legal_name.strip():
return 0
if not isinstance(country, str) or not _COUNTRY_PATTERN.fullmatch(country):
return 0
if not isinstance(tax_id, str):
return 0
clean_id = _strip_tax_id(tax_id)
if not (8 <= len(clean_id) <= 10) or not clean_id.isalnum() or not clean_id.isascii():
return 0
# --- Tier 2: registry match ---
reg_country = registry.get("country")
reg_tax_id = registry.get("tax_id")
reg_name = registry.get("legal_name")
if not isinstance(reg_country, str) or country.lower() != reg_country.lower():
return 1
if not isinstance(reg_tax_id, str) or clean_id.upper() != _strip_tax_id(reg_tax_id).upper():
return 1
sub_tokens = _name_tokens(legal_name, drop_suffixes=True)
reg_tokens = _name_tokens(reg_name, drop_suffixes=True)
if not sub_tokens or sub_tokens != reg_tokens:
return 1
# --- Tier 3: ownership match ---
owners = submitted.get("owners", [])
reg_owners = registry.get("owners", [])
if not isinstance(owners, list) or not owners or not isinstance(reg_owners, list):
return 2
reg_owner_token_sets = [_name_tokens(o) for o in reg_owners if isinstance(o, str)]
if all(_name_tokens(o) in reg_owner_token_sets for o in owners if isinstance(o, str)):
return 3
return 2