Parcel Attribute Store with TTL and Prefix Queries
Data Structure DesignAuto-graded · 20 test casesLast updated
Simulate a timestamped key-value attribute store with overwrite, conditional update, sorted prefix listing, and per-attribute expiry.
You are given a list of operation names and a parallel list of argument lists. Process them in order against an in-memory store of parcels. Each parcel is identified by a string parcel ID and holds attributes, each having a name, a single value, and an expiration deadline. Every argument list begins with a non-negative integer timestamp. Produce a result for each operation, appended in the order the operations are processed, and return the list of results.
Supported operations:
-
"set": args are(timestamp, parcel_id, attribute, value)or(timestamp, parcel_id, attribute, value, ttl). Storevalueunderattributefor the parcel, replacing any prior value and deadline. Ifttlis omitted treat it as0. Attlof0means the attribute never expires; otherwise the attribute expires exactlyttltime units aftertimestamp, i.e. it is live at timetif and only ift < timestamp + ttl. Result:None. -
"get": args are(timestamp, parcel_id, attribute). Result: the attribute's value if it exists and is live attimestamp, otherwiseNone. -
"update_if_match": args are(timestamp, parcel_id, attribute, expected, new_value)or(timestamp, parcel_id, attribute, expected, new_value, ttl). If the attribute exists, is live attimestamp, and its current value equalsexpectedexactly, replace its value withnew_valueand its deadline according tottl(omitted means0, meaning never expires); resultTrue. Otherwise change nothing and resultFalse. This operation cannot create a missing attribute. -
"list_attributes": args are(timestamp, parcel_id). Result: a list of strings, one per live attribute of the parcel, each formatted asname(value), ordered ascending by attribute name using plain string comparison. -
"list_attributes_with_prefix": args are(timestamp, parcel_id, prefix). Same aslist_attributesbut only attributes whose names start withprefixare included.
An unknown parcel behaves like a parcel with no attributes. Expired attributes are treated as absent for all reads and for the conditional update; you may either hide them or delete them. When a write succeeds, the new lifetime starts from that call's timestamp using that call's ttl.
Constraints
1 <= len(operations) <= 10^4len(arguments) == len(operations), and argument lists have the lengths described above.timestampis a non-negative integer and is non-decreasing across calls.ttlis a non-negative integer;ttl == 0means the attribute never expires.- Attribute names and values are strings; matching in
update_if_matchis exact and case-sensitive. - An unknown operation should raise
ValueError, but valid inputs only contain the five operations above.
Examples
Example 1
Input: process_parcel_operations(['set', 'get', 'update_if_match', 'get', 'list_attributes', 'list_attributes_with_prefix'], [[1, 'p1', 'color', 'blue'], [2, 'p1', 'color'], [3, 'p1', 'color', 'blue', 'green'], [4, 'p1', 'color'], [5, 'p1'], [6, 'p1', 'co']])
Output: [None, 'blue', True, 'green', ['color(green)'], ['color(green)']]
Example 2
Input: process_parcel_operations(['set', 'get', 'get', 'list_attributes'], [[10, 'p2', 'size', 'large', 5], [14, 'p2', 'size'], [15, 'p2', 'size'], [15, 'p2']])
Output: [None, 'large', None, []]
Hints
Hint 1
Store each parcel as a dict mapping attribute name to a pair (value, expiry_timestamp), where expiry_timestamp is None for attributes that never expire.
Hint 2
Write one helper that decides whether an entry is live at a given timestamp: ttl 0 means always live, otherwise live only when timestamp < expiry, so the entry is dead starting exactly at expiry.
Hint 3
For listings, collect the live names, sort them, then format each as name(value); for the prefix version reuse that same code with an extra name.startswith(prefix) filter.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Keep a two-level dictionary: the outer key is the parcel ID, and the inner key is the attribute name. Each inner value is a pair (value, expires_at), where expires_at is None when the attribute never expires, or the integer time write_time + ttl at which it stops being live.
A single liveness predicate drives every read: an entry is live at time t when expires_at is None or t < expires_at. Because the check is strictly less-than, an attribute written at time w with ttl d is visible for t = w, ..., w + d - 1 and is gone at t = w + d.
Process operations in order, appending one result each:
setcomputes the new pair and overwrites whatever was stored (or creates the parcel dict if needed), then appendsNone. An omitted ttl defaults to0, i.e. non-expiring.getlooks up the entry; if it is missing or not live, appendNone, otherwise the stored value.update_if_matchsucceeds only if the entry exists, is live at the timestamp, and its value equalsexpected. On success it writes the new value with a fresh deadline computed from this call's timestamp and ttl, and appendsTrue; otherwise it appendsFalseand leaves the store untouched. It never creates a missing attribute.list_attributesiterates the parcel's attribute names, keeps the live ones, sorts the names, and formats each asname(value).list_attributes_with_prefixis identical but additionally requiresname.startswith(prefix).
Correctness: the liveness rule is applied uniformly to get, both listings, and the conditional update, so expired entries are consistently invisible. Sorting before formatting yields the required ascending name order, and the name(value) template matches the specified output format. Treating unknown parcels as empty dicts produces empty listings and None/False results as required.
Complexity: each set, get, and update_if_match is O(1) expected time. Each listing is O(a log a) for a parcel with a stored attributes. Total space is O(total attributes stored).