progress

~/problems / Files & networks / DNS resolver

Exact and wildcard records, most specific wins

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A host serves customer shops under *.shops.example, but some shops have their own server and the *.eu.shops.example region lives elsewhere. A name is answered by the most specific record covering it.

Implement lookup(name: str, records: dict[str, str]) -> str | None. Names are lowercase dotted labels. A key is an exact name or a wildcard "*." + S, which covers names ending in "." + S with at least one label before it (*.shops.example covers a.b.shops.example, not shops.example).

Return the exact record if there is one, else the covering wildcard with the longest suffix, else None.

records = {
    "*.shops.example":      "10.0.0.1",
    "*.eu.shops.example":   "10.0.9.9",
    "bakery.shops.example": "10.0.0.50",
    "shops.example":        "10.0.0.2",
}
lookup("bakery.shops.example", records)     # "10.0.0.50"  exact
lookup("cake.shops.example", records)       # "10.0.0.1"   *.shops.example
lookup("cake.eu.shops.example", records)    # "10.0.9.9"   the longer wildcard wins
lookup("eu.shops.example", records)         # "10.0.0.1"   *.eu.shops.example needs a label before "eu"
lookup("shops.example", records)            # "10.0.0.2"
lookup("example", records)                  # None

⭐ Bonus: scanning every record per lookup still passes; a speed test with 300 lookups in a 30,000-record zone earns a star if you only check the handful of suffixes of name.

Show hint

try records.get(name), then "*." + ".".join(labels[i:]) for i = 1, 2, ...; the first hit has the longest suffix.

Topic: DNS resolver. Recursive CNAME resolution, cycle detection, TTL cache.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc