Batch Simulator for a TTL-Aware Name Lookup Service with Aliases
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a batch of record insertions and lookups with normalized names, TTL expiry, alias-chain following, cycle and hop-limit detection, and A/alias exclusivity.
You are building a small in-memory name-lookup service, similar to DNS, and you must replay a batch of commands against it. Implement one function that processes the commands in order and returns one result per command.
Inputs
operations: a list of command names. Each is either"add_record"or"resolve".arguments: a list of the same length.arguments[i]holds the parameters foroperations[i]:- for
"add_record":[name, record_type, value, ttl, current_time] - for
"resolve":[name, record_type, current_time]
- for
Output
A list with one entry per command, in the same order:
Nonefor every"add_record"command.- A list of strings for every
"resolve"command.
Record types
"A"maps a name to an address string such as"192.0.2.1". A name may hold several differentAvalues at once."CNAME"maps a name (the alias) to another name (the target). A name holds at most oneCNAME.- Record types are case-insensitive, so
"a"and"cname"are accepted. Any other record type in anadd_recordcommand is ignored and stores nothing.
Rules
Name normalization. Names are case-insensitive and may end with one trailing dot. To normalize a name, convert it to lowercase and then remove a single trailing . if present. Do not do anything else to it, such as trimming whitespace or removing further dots. Normalize the name argument of both commands and also the value of a CNAME record, because it is a name. The value of an A record is stored exactly as given.
Expiry. An add_record with ttl and current_time creates a record that expires at current_time + ttl. The record is valid for a query at time t only if t < current_time + ttl. At t equal to the expiry time, or later, the record is expired and must be ignored. A record with ttl <= 0 is therefore never valid. Time values never decrease from one command to the next.
Adding an A record.
- If the name currently holds a valid
CNAME, thatCNAMEis removed. This happens even if the newArecord hasttl <= 0. - The
Avalue is then added to the name's set ofAvalues. - Adding the same
Avalue again does not remove earlier insertions. A value counts as present if at least one of its insertions is still valid.
Adding a CNAME record.
- All
Avalues stored for that name are removed. - Any existing
CNAMEfor the name is replaced by the new one.
Resolving a CNAME query. Return a one-element list containing the normalized target if the name has a valid CNAME, otherwise []. The chain is not followed.
Resolving an A query. Start at the normalized name and repeat the following:
- If the current name has already been visited during this query, there is a cycle. Return
[]. - Mark the current name as visited.
- If the current name has a valid
CNAME:- If 10
CNAMElinks have already been followed in this query, return[]. - Otherwise follow the link: the target becomes the current name, count one more hop, and go back to step 1.
- If 10
- Otherwise, return the sorted list of distinct valid
Avalues stored for the current name. This is[]if there are none, if the name is unknown, or if all of itsAvalues have expired.
A valid CNAME always takes priority over A values at the same name. An expired CNAME is treated as if it does not exist.
Resolving any other record type. Return [].
Result lists of A values are sorted in ascending string order and contain no duplicates.
Constraints
operationsandargumentshave the same length, and there is at least one command.- Every command name is
"add_record"or"resolve". name,valueand record types are strings.ttlandcurrent_timeare integers, andttlmay be zero or negative.current_timedoes not decrease across consecutive commands.- At most 10
CNAMElinks may be followed in a singleAquery. Needing an 11th link makes the query return[].
Examples
Example 1
Input: simulate_name_service(['add_record', 'add_record', 'resolve', 'resolve', 'resolve'], [['example.com', 'A', '93.184.216.34', 60, 100], ['www.example.com.', 'CNAME', 'example.com', 60, 100], ['EXAMPLE.COM.', 'A', 120], ['www.example.com', 'A', 150], ['www.example.com', 'A', 170]])
Output: [None, None, ['93.184.216.34'], ['93.184.216.34'], []]
Hints
Hint 1
Normalize names once at the entry of every command, including the target value of a CNAME, so that all later lookups are exact dictionary matches.
Hint 2
Store absolute expiry times (current_time + ttl) rather than TTLs. For repeated A values keep the latest expiry, so a value is valid if any of its insertions is still valid.
Hint 3
Resolve an A query with a loop: keep a visited set for cycles and a hop counter that fails when an 11th link would be needed. A valid CNAME is checked before the A values at each name.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Normalize every name once, when a command arrives. After that, all lookups are exact dictionary matches. Keep two maps:
a_records: name -> {address: latest expiry}. A dictionary per name removes duplicate addresses. Keeping the maximum expiry means an address is valid if any of its insertions is still valid.cnames: name -> (normalized target, expiry). There is at most one entry per name.
Store absolute expiry times (current_time + ttl), so a record is valid exactly when now < expiry.
add_record
- For an
Arecord, drop the name'sCNAMEif it is currently valid, then record the address with its expiry. - For a
CNAMErecord, drop allAvalues for the name and store the new alias with its normalized target. - Any other type stores nothing. Every
add_recordyieldsNone.
resolve
- A
CNAMEquery returns the direct target if it is valid, and[]otherwise. - An
Aquery walks the chain in a loop:- A
visitedset detects cycles. A repeated name returns[]. - If the current name has a valid
CNAME, the walk follows it. If 10 links were already followed, it returns[]. - Otherwise the answer is the sorted list of valid
Aaddresses at the current name, which may be empty.
- A
- Any other type returns
[].
Why it is correct
- Normalization is applied to command names and to
CNAMEtargets, so aliases and queries always agree on keys. - Every read compares against the absolute expiry, so expired records are never visible. Boundary equality counts as expired.
- Checking for a valid
CNAMEbefore readingAvalues gives aliases priority. The write rules keep a validCNAMEandAvalues from coexisting at one name anyway. - Each loop iteration either returns or moves to a name not seen before, so the loop terminates. The hop counter enforces the limit of 10 followed links separately from cycle detection.
Complexity
add_recordtakes O(1) on average. Adding aCNAMEalso discards the name'sAvalues, which costs time proportional to how many there are.resolvefor anAquery visits at most 11 names and sorts the final answer, so it takes O(k log k), where k is the number ofAvalues at the final name.- Space is O(R) for R stored records.
Reference solution
from typing import List
def simulate_name_service(operations: List[str], arguments: List[List[object]]) -> List[object]:
MAX_HOPS = 10
a_records = {} # name -> {value: latest expiry}
cnames = {} # name -> (normalized target, expiry)
results = []
def normalize(name):
name = name.lower()
return name[:-1] if name.endswith(".") else name
for operation, params in zip(operations, arguments):
if operation == "add_record":
name, record_type, value, ttl, now = params
name = normalize(name)
record_type = record_type.upper()
expiry = now + ttl
if record_type == "A":
link = cnames.get(name)
if link is not None and now < link[1]:
del cnames[name]
values = a_records.setdefault(name, {})
if value not in values or expiry > values[value]:
values[value] = expiry
elif record_type == "CNAME":
a_records.pop(name, None)
cnames[name] = (normalize(value), expiry)
results.append(None)
elif operation == "resolve":
name, record_type, now = params
name = normalize(name)
record_type = record_type.upper()
if record_type == "CNAME":
link = cnames.get(name)
if link is not None and now < link[1]:
results.append([link[0]])
else:
results.append([])
continue
if record_type != "A":
results.append([])
continue
visited = set()
hops = 0
current = name
answer = []
while True:
if current in visited:
answer = []
break
visited.add(current)
link = cnames.get(current)
if link is not None and now < link[1]:
if hops >= MAX_HOPS:
answer = []
break
current = link[0]
hops += 1
continue
answer = sorted(
v for v, exp in a_records.get(current, {}).items() if now < exp
)
break
results.append(answer)
else:
raise ValueError("Unknown operation")
return results