Card Prefix Registry with Per-Field Trust Resolution
Data Structure DesignModel answerLast updated
Design an in-memory registry mapping digit prefixes to brand and card type, resolving each field by longest prefix, then trust, then recency, with fast lookups.
Card Prefix Registry with Per-Field Trust Resolution
You are building an in-memory registry that maps leading digits of payment card numbers to descriptive attributes. Write a function process_bin_operations(operations) that executes a list of operations in order and returns the answers to all lookups, in the order they appeared.
Operations
Each operation is a tuple of one of two shapes:
("store", prefix, source, trust, brand, card_type)records a new report about a prefix.("lookup", card_number)asks for the brand and card type of a full card number.
For a store, prefix, source, brand and card_type are strings (the last two may be None), and trust is an integer. At least one of brand and card_type is non-None. Every store counts as a brand-new report, even if an earlier store had the same source and values.
Resolution rules for a lookup
brand and card_type are resolved separately. For each one:
- Collect every stored prefix that is a leading substring of
card_numberand whose reports supplied a value for that field. - Choose the longest such prefix.
- Among the reports at that prefix that supplied the field, choose the one with the highest
trust. - If trust is tied, choose the most recently stored report.
A report that leaves a field as None must never overwrite or hide an older value for that field. A lookup returns (brand, card_type), using None for any field with no qualifying report.
Constraints
1 <= len(operations) <= 200,000- Prefixes and card numbers consist of decimal digits only.
1 <= len(prefix) <= 32,len(card_number) <= 64sourceis just metadata; different sources may report identical values.- All inputs are valid.
Example
Suppose a 6-digit prefix reports a high-trust brand with no card type, and a longer 8-digit prefix, which the card number also starts with, reports only a card type. Looking up that card yields the brand from the 6-digit prefix and the type from the 8-digit one. If a later report at the same prefix has equal trust, it replaces the earlier value only for the field(s) it actually supplies.
What to cover
Explain your data structure and why it handles heavy lookup traffic, state the time and space complexity, and write the code. Mention the edge cases you would test.
Hints
Hint 1
Because writes are never deleted, you do not need to keep every report. For each (prefix, field) pair, only the current best report can ever matter.
Hint 2
A new report is always the most recent one so far. So at a given prefix and field it wins exactly when its trust is greater than or equal to the stored winner's trust, and a None field simply skips the update.
Hint 3
Stored prefixes are at most 32 digits, so a lookup only needs to check at most 32 candidate prefixes of the card number, from longest to shortest. Fill each field from the first prefix that has it and stop when both are filled.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying the contract
Before coding, I would confirm the following:
- Fields are independent. One lookup may take its brand from a 6-digit prefix and its type from an 8-digit prefix.
- Specificity beats trust. Trust only compares reports at the same prefix. A low-trust longer prefix beats a high-trust shorter one.
- Recency breaks trust ties. A repeated identical store still counts as newer, though that is unobservable.
Nonemeans "not supplied" and never erases anything.sourcehas no effect on resolution.- Lookups dominate, so their cost should not grow with the number of stored reports.
Key observations
1. Only one winner per (prefix, field) is needed. Reports are never removed, and the ordering at a prefix is "higher trust, then newer". A new report is newer than everything stored, so it beats the current winner exactly when new_trust >= old_trust. No sequence numbers need to be compared or stored. A report with brand=None does not touch the brand slot, which gives the no-erasure rule for free.
2. Prefix length is bounded by 32. For a card number c, the only possible matching prefixes are c[:L] for L <= min(32, len(c)). That is a tiny, fixed candidate set regardless of how many reports exist.
Data structure
- A hash map
table: prefix -> [brand_slot, type_slot], where each slot isNoneor(trust, value). - A descending list of the distinct prefix lengths that have been stored (at most 32), so lookups skip lengths that cannot match.
A digit trie is an alternative: walk down the card number, remembering the deepest node that has a brand and the deepest that has a type. It gives O(32) lookups, but in Python up to 200,000 x 32 nodes is memory-heavy. The hash map is leaner and easier to get right. I would mention both and justify the choice.
Algorithm
Store: find or create the slot pair for prefix (registering its length if new). For each non-None field, replace the slot if it is empty or trust >= slot.trust.
Lookup: for each stored length L from longest to shortest with L <= len(card), fetch table.get(card[:L]). If the brand is still unresolved and this prefix has a brand, take it. Do the same for type. Stop early when both are resolved.
Why it is correct
- Descending length order means the first prefix that holds a given field is the longest qualifying one. Prefixes that exist but lack the field have an empty slot and are skipped, so a type-only prefix never blocks a brand from a shorter prefix.
- Each slot holds the maximum under (trust, recency) among the reports that supplied that field. By induction over writes, each new report is the newest, so it is maximal iff its trust is at least the current maximum. Reports omitting the field are not candidates and leave the slot alone.
- Brand and type use separate slots and separate "found" flags, so merging across prefixes falls out naturally.
Complexity
Let K <= 32 be the number of distinct stored lengths.
| Operation | Time |
|---|---|
| Store | O(len(prefix)), at most 32 |
| Lookup | O(K x 32) worst case, since each probe slices and hashes up to 32 characters |
| Whole input | O(n x 32^2) worst case, effectively linear in n |
Lookup time is independent of how many reports were stored. Space is O(D x 32) for D distinct prefixes, at most O(n), because only winners are kept.
Code
from typing import List, Optional, Tuple
def process_bin_operations(operations) -> List[Tuple[Optional[str], Optional[str]]]:
table = {} # prefix -> [brand_slot, type_slot]; slot = (trust, value) or None
lengths_desc: List[int] = []
length_seen = set()
results = []
for op in operations:
if op[0] == "store":
_, prefix, _source, trust, brand, card_type = op
slots = table.get(prefix)
if slots is None:
slots = [None, None]
table[prefix] = slots
L = len(prefix)
if L not in length_seen:
length_seen.add(L)
lengths_desc.append(L)
lengths_desc.sort(reverse=True)
if brand is not None:
cur = slots[0]
if cur is None or trust >= cur[0]:
slots[0] = (trust, brand)
if card_type is not None:
cur = slots[1]
if cur is None or trust >= cur[0]:
slots[1] = (trust, card_type)
else:
card = op[1]
n = len(card)
brand_res = type_res = None
got_brand = got_type = False
for L in lengths_desc:
if L > n:
continue
slots = table.get(card[:L])
if slots is None:
continue
if not got_brand and slots[0] is not None:
brand_res, got_brand = slots[0][1], True
if not got_type and slots[1] is not None:
type_res, got_type = slots[1][1], True
if got_brand and got_type:
break
results.append((brand_res, type_res))
return results
Edge cases to test
- Card shorter than every stored prefix gives
(None, None); an empty card number also gives(None, None). - Card equal to a stored prefix counts as a match.
- A type-only long prefix must not hide the brand from a shorter prefix.
- Equal trust, later write: wins, but only for the fields it supplies.
- Lower trust, later write at the same prefix: loses there, yet the prefix still beats any shorter one.
- Zero or negative trust: plain integer comparison still works.
- Same values from different sources: harmless.
- Lookup before any store.
Common mistakes
- Letting trust override prefix length.
- Treating a write as a whole record, so a
Nonefield erases an older value. - Using strict
>for replacement, which breaks the recency tie-break. - Scanning all stored reports per lookup, which is O(n) and too slow at 200,000 operations.
- Stopping at the longest matching prefix instead of continuing for the field it lacks.