Card Prefix Attribute Store with Trust Priority
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement process_bin_operations(operations) to simulate an in-memory card-prefix registry that resolves two card attributes — brand and card_type — across an ordered stream of writes and queries. Return a list containing one (brand, card_type) tuple for each query in the order the queries occur.
Each element of operations takes one of two forms:
("store", prefix, source, trust, brand, card_type)— appends a write for the digit stringprefix, tagged with feed identifiersource(str) and reliability scoretrust(int). At least one ofbrandorcard_typeis a non-Nonestring; an omitted attribute is passed asNone. Every"store"entry counts as a fresh arrival even ifprefix,source,trust, and attribute values match a prior write.("lookup", card_number)— resolves(brand, card_type)for the digit stringcard_numberusing only"store"entries processed earlier inoperations.
During a "lookup", evaluate brand and card_type separately using the following precedence order:
- Candidate filter: Keep only prior writes whose
prefixis a leading prefix ofcard_number(card_number.startswith(prefix)) and whose value for the attribute being resolved is notNone. - Specificity first: Choose writes with the greatest
len(prefix), even when a shorter matching prefix carries a highertrustscore. - Reliability tie-breaker: Among writes sharing that longest matching prefix, choose those with the largest
trustvalue. - Recency tie-breaker: If multiple writes at that prefix tie on
trust, choose the write that appeared latest inoperations.
An attribute passed as None during a "store" never deletes or masks an earlier non-None value for that attribute. If no prior write matches card_number for a given attribute, return None in that slot of the (brand, card_type) tuple.
Examples
Example 1
operations = [
("store", "520010", "feed_alpha", 8, "MASTERCARD", None),
("store", "52001088", "feed_beta", 2, None, "PREPAID"),
("lookup", "5200108812345678"),
("lookup", "5200104400001111"),
("store", "520010", "feed_gamma", 8, "MC_WORLD", "CREDIT"),
("lookup", "5200108812345678"),
("lookup", "5200104400001111"),
]
Output:
[
("MASTERCARD", "PREPAID"),
("MASTERCARD", None),
("MC_WORLD", "PREPAID"),
("MC_WORLD", "CREDIT"),
]
Walk-through:
- On the first lookup ("5200108812345678"), "520010" supplies "MASTERCARD" for brand while the longer "52001088" supplies "PREPAID" for card_type, producing ("MASTERCARD", "PREPAID").
- On the second lookup ("5200104400001111"), only "520010" matches, so card_type has no matching write and resolves to None.
- Next, "feed_gamma" writes ("MC_WORLD", "CREDIT") at "520010" with equal trust 8; because it arrived later, "MC_WORLD" replaces "MASTERCARD" at "520010", and "CREDIT" fills the previously empty card_type slot at "520010".
- On the third lookup ("5200108812345678"), brand resolves to "MC_WORLD" from "520010", while card_type still resolves to "PREPAID" from "52001088" (trust = 2) because prefix length 8 beats prefix length 6 (trust = 8).
- On the fourth lookup ("5200104400001111"), "520010" supplies both attributes, yielding ("MC_WORLD", "CREDIT").
Example 2
operations = [
("store", "34", "issuer_db", 50, "AMEX", "CHARGE"),
("store", "3412", "partner_csv", 3, "AMEX_CORP", None),
("store", "3412", "manual_fix", 1, "WRONG_BRAND", None),
("lookup", "341299001122334"),
("lookup", "349900001111222"),
]
Output:
[
("AMEX_CORP", "CHARGE"),
("AMEX", "CHARGE"),
]
Walk-through:
- At "3412", "partner_csv" (trust = 3) outranks the later "manual_fix" (trust = 1), so "AMEX_CORP" remains the winning brand at "3412".
- When looking up "341299001122334", "3412" (length 4) wins brand over "34" (length 2, trust = 50), whereas card_type falls back to "34" ("CHARGE") because no write at "3412" provided card_type.
- When looking up "349900001111222", "3412" does not match, so both attributes come from "34".
Constraints
1 <= len(operations) <= 200,0001 <= len(prefix) <= 32, consisting solely of ASCII digits'0'–'9'.0 <= len(card_number) <= 64, consisting solely of ASCII digits'0'–'9'.trustis an arbitrary Python integer (negative, zero, or positive).- Every
"store"operation provides at least one non-Nonevalue amongbrandandcard_type. sourceis retained as write metadata; multiple writes may share the samesourceor attribute values.- All operation tuples are well-formed; input validation is unnecessary.
Step-by-step walkthrough
Understand BIN prefix matching and field-by-field rules
In payment processing, a card's leading digits are called its BIN (Bank Identification Number — traditionally the first
6digits, and often the first8digits in modern card ranges). Different data feeds report card attributes (brandsuch as"VISA"andcard_typesuch as"DEBIT") at different prefix lengths and with differenttrustscores.When looking up a
card_number, we resolvebrandandcard_typecompletely independently using three tie-breakers in strict priority order:- Longest matching prefix first: Among all stored prefixes that start
card_numberand provided a non-Nonevalue for that field, pick the longest prefix — even if a shorter prefix has much highertrust! - Highest trust at that prefix: If several writes targeted that exact same winning prefix, pick the one with the largest integer
trust. - Most recent write on trust ties: If two writes at that prefix share the highest
trust, pick whichever arrived later inoperations(even if itssourceand values repeat an earlier write).
Let's also note the edge-case rules up front: - A
Nonefield means "not provided by this write" — it never deletes or overwrites an older value for that field. - A prefix equal in length to the entirecard_numberis a valid match; a prefix longer thancard_numbercannot match. - Operations are processed strictly in order, so a"lookup"sees only"store"operations that came before it.- Longest matching prefix first: Among all stored prefixes that start
Start with a brute-force scan and see why it times out
The most direct way to check our understanding is to append every
"store"to a listwritesalong with its arrivalindex, and scan all earlier writes on every"lookup"using the comparison tuple(len(prefix), trust, index):def brute_lookup(writes, card_number): """writes: list of (prefix, trust, index, brand, card_type) in arrival order.""" best_values = [None, None] best_keys = [None, None] for prefix, trust, index, brand, card_type in writes: if not card_number.startswith(prefix): continue fields = [brand, card_type] for slot in range(2): candidate_key = (len(prefix), trust, index) if fields[slot] is not None and (best_keys[slot] is None or candidate_key > best_keys[slot]): best_keys[slot] = candidate_key best_values[slot] = fields[slot] return (best_values[0], best_values[1])Why is this too slow? Each lookup scans all
Wwrites seen so far (O(W)). With200,000operations — say100,000stores followed by100,000lookups — that performs100,000 * 100,000 = 10^10prefix checks, taking minutes instead of milliseconds!Key idea 1: collapse all writes at one prefix into two winner slots
Focus on a single prefix (say
"520010") and one field (saybrand). Multiple stores may write to"520010"over time, and among them we only ever want the one with the largest(trust, arrival_index).Because writes are never deleted, any write that loses at
"520010"today can never win a future lookup! Even better, because we processoperationsin chronological order, every incoming write automatically has a largerarrival_indexthan whatever is currently stored. That collapses the two-part(trust, recency)rule into one simple check:Incoming write at prefix "520010" with (trust, value, source): - value is None --> ignore! Omitted fields never erase existing winners. - slot is empty --> store (trust, value, source) - trust > current_winner[0] --> higher trust wins: overwrite slot - trust == current_winner[0] --> tie on trust, and new write is more recent: overwrite slot! - trust < current_winner[0] --> older higher-trust winner stays in place Combined condition: current_winner is None or trust >= current_winner[0]Notice why
>=(instead of>) is critical: using>would keep the oldest write on trust ties instead of the most recent write!Key idea 2: probe distinct stored lengths from longest to shortest
Now how do we find the longest matching prefix of
card_numberwithout scanning every key inprefix_winners?Look at the constraint
1 <= len(prefix) <= 32. Acard_numbercan have at most 32 candidate prefixes of length<= 32:card_number[:32],card_number[:31], ...,card_number[:1]. Even better, we only need to check prefix lengthsLthat have actually been stored at least once (in real payment systems, almost always just[8, 6]).card_number = "5200108812345678", sorted_lengths = [8, 6] (longest first!) 1. Probe length 8 -> slice "52001088" in dict -> [brand=None, type="PREPAID"] resolved_type becomes "PREPAID" (resolved_brand still None) 2. Probe length 6 -> slice "520010" in dict -> [brand="MC_WORLD", type="CREDIT"] resolved_brand becomes "MC_WORLD" (resolved_type ALREADY set, so keep "PREPAID"!) 3. Both fields filled -> break early! Return ("MC_WORLD", "PREPAID").Because
sorted_lengthsruns strictly from longest to shortest, the very first matching prefix with a non-Nonebrand is guaranteed to be the longest matching prefix forbrand— and likewise independently forcard_type!Code the per-slot store helper
Let's write
_update_slotand the"store"branch. We retainsourceinside theWinner = (trust, value, source)tuple as write metadata, and maintainseen_lengthsalongsidesorted_lengthssosorted_lengths.sort(reverse=True)runs at most 32 times across the entire200,000-operation workload:from typing import List, Optional, Tuple BRAND_SLOT = 0 TYPE_SLOT = 1 Winner = Tuple[int, str, str] def _update_slot( slots: List[Optional[Winner]], slot_idx: int, trust: int, value: Optional[str], source: str, ) -> None: """Update one field's winning write at its prefix if `value` is present and wins `(trust, recency)`.""" if value is None: return current_winner = slots[slot_idx] if current_winner is None or trust >= current_winner[0]: slots[slot_idx] = (trust, value, source)Code the longest-prefix lookup helper
In
_lookup_card, we skip anyprefix_len > len(card_number)(since a prefix longer than the card number cannot match), look upcard_number[:prefix_len]inprefix_winnersinO(1)hash-table time, fill whichever ofresolved_brandorresolved_typeis stillNone, andbreakas soon as both are found:from typing import Dict, List, Optional, Tuple def _lookup_card( prefix_winners: Dict[str, List[Optional[Winner]]], sorted_lengths: List[int], card_number: str, ) -> Tuple[Optional[str], Optional[str]]: """Resolve `brand` and `card_type` independently using longest-prefix match.""" resolved_brand: Optional[str] = None resolved_type: Optional[str] = None card_len = len(card_number) for prefix_len in sorted_lengths: if prefix_len > card_len: continue candidate_prefix = card_number[:prefix_len] slots = prefix_winners.get(candidate_prefix) if slots is None: continue if resolved_brand is None and slots[BRAND_SLOT] is not None: resolved_brand = slots[BRAND_SLOT][1] if resolved_type is None and slots[TYPE_SLOT] is not None: resolved_type = slots[TYPE_SLOT][1] if resolved_brand is not None and resolved_type is not None: break return (resolved_brand, resolved_type)Trace Example 1 step by step
Let's trace how the
6-digit prefix"520010"and8-digit prefix"52001088"from Example 1 interact across stores and lookups:Operation Table state after store / Lookup trace -------------------------------------------------------- -------------------------------------------------------------- 1. store("520010", "feed_alpha", 8, "MASTERCARD", None) prefix_winners["520010"] = [(8, "MASTERCARD", "feed_alpha"), None] 2. store("52001088", "feed_beta", 2, None, "PREPAID") prefix_winners["52001088"] = [None, (2, "PREPAID", "feed_beta")] sorted_lengths = [8, 6] 3. lookup("5200108812345678") L=8 "52001088" -> type="PREPAID"; L=6 "520010" -> brand="MASTERCARD" --> returns ("MASTERCARD", "PREPAID") 4. lookup("5200104400001111") L=8 "52001044" -> miss; L=6 "520010" -> brand="MASTERCARD", type=None --> returns ("MASTERCARD", None) 5. store("520010", "feed_gamma", 8, "MC_WORLD", "CREDIT") At "520010": brand 8 >= 8 -> "MC_WORLD"; type empty -> "CREDIT" 6. lookup("5200108812345678") L=8 "52001088" -> type="PREPAID" (trust 2 at L=8 beats trust 8 at L=6!) L=6 "520010" -> brand="MC_WORLD" --> returns ("MC_WORLD", "PREPAID") 7. lookup("5200104400001111") L=8 miss; L=6 "520010" supplies both --> returns ("MC_WORLD", "CREDIT")Look closely at step 6: even though
"feed_gamma"wrote"CREDIT"withtrust = 8at"520010","5200108812345678"still gets"PREPAID"from"52001088"(trust = 2) because longest prefix (8 > 6) always wins before trust is compared.Complete solution
from typing import Dict, List, Optional, Set, Tuple # Slot indices inside each prefix's two-element winner list: [brand_winner, type_winner]. BRAND_SLOT = 0 TYPE_SLOT = 1 # Winner tuple for a single field at a single prefix: (trust_score, field_value, source_name). Winner = Tuple[int, str, str] def _update_slot( slots: List[Optional[Winner]], slot_idx: int, trust: int, value: Optional[str], source: str, ) -> None: """Update one field's winning write at its prefix if `value` is present and wins `(trust, recency)`.""" # An omitted field (`None`) expresses no opinion and must never erase an existing value. if value is None: return current_winner = slots[slot_idx] # Because operations arrive in chronological order, this write is strictly newer than `current_winner`. # Using `>=` (not `>`) ensures equal-trust ties go to the most recent write. if current_winner is None or trust >= current_winner[0]: slots[slot_idx] = (trust, value, source) def _lookup_card( prefix_winners: Dict[str, List[Optional[Winner]]], sorted_lengths: List[int], card_number: str, ) -> Tuple[Optional[str], Optional[str]]: """Resolve `brand` and `card_type` independently using longest-prefix match.""" resolved_brand: Optional[str] = None resolved_type: Optional[str] = None card_len = len(card_number) # Walk distinct stored prefix lengths from longest to shortest (at most 32 lengths). # Because prefix length beats trust, the first matching prefix that supplies a field wins that field. for prefix_len in sorted_lengths: if prefix_len > card_len: continue candidate_prefix = card_number[:prefix_len] slots = prefix_winners.get(candidate_prefix) if slots is None: continue if resolved_brand is None and slots[BRAND_SLOT] is not None: resolved_brand = slots[BRAND_SLOT][1] if resolved_type is None and slots[TYPE_SLOT] is not None: resolved_type = slots[TYPE_SLOT][1] # Stop early once both fields are filled; shorter prefixes can never override longer ones. if resolved_brand is not None and resolved_type is not None: break return (resolved_brand, resolved_type) def process_bin_operations(operations: List[Tuple]) -> List[Tuple[Optional[str], Optional[str]]]: """Apply `store` and `lookup` operations in arrival order and return one `(brand, card_type)` per lookup.""" # prefix_winners: dict mapping prefix -> [brand_winner_or_None, type_winner_or_None]. prefix_winners: Dict[str, List[Optional[Winner]]] = {} # sorted_lengths: distinct stored prefix lengths sorted longest-first (at most 32 ints). sorted_lengths: List[int] = [] # seen_lengths: set of ints already present in `sorted_lengths` for O(1) membership checks. seen_lengths: Set[int] = set() lookup_results: List[Tuple[Optional[str], Optional[str]]] = [] for op in operations: op_kind = op[0] if op_kind == "store": _, prefix, source, trust, brand, card_type = op # Phase 1: Ensure this prefix has a two-slot winner entry and record its length if new. slots = prefix_winners.get(prefix) if slots is None: slots = [None, None] prefix_winners[prefix] = slots prefix_len = len(prefix) if prefix_len not in seen_lengths: seen_lengths.add(prefix_len) sorted_lengths.append(prefix_len) sorted_lengths.sort(reverse=True) # Phase 2: Offer `brand` and `card_type` independently to their respective slots. _update_slot(slots, BRAND_SLOT, trust, brand, source) _update_slot(slots, TYPE_SLOT, trust, card_type, source) else: # Phase 3: Answer lookup using only writes processed so far. card_number = op[1] lookup_results.append(_lookup_card(prefix_winners, sorted_lengths, card_number)) return lookup_results✅ Submit now — all tests should pass.
Intuition & how it works
Think of a BIN (Bank Identification Number, the leading digits on a payment card) database like nested postal rules: a broad city-wide rule (6-digit prefix "520010") might tell you the card network is "MASTERCARD" without specifying the card type, while a specific street-block rule (8-digit prefix "52001088") specifies "PREPAID" without repeating the network. For each field on its own, we want a longest-prefix match (always preferring the most specific matching prefix before considering trust or timestamps), and only when multiple writes hit that exact same prefix do we apply lexicographic tie-breaking (comparing (trust, recency) in order: highest trust first, then newest arrival). Because writes are never deleted, each prefix only needs to remember two winning slots — its best brand write and its best card_type write — and because prefixes are at most 32 digits long, a lookup simply slices card_number[:L] across the distinct stored prefix lengths L from longest to shortest!
Why do naive approaches fall short? Appending every write to a list and scanning all W writes on each lookup costs O(W) per lookup, turning 100,000 stores and 100,000 lookups into 10 billion string checks. Equally important, storing a single combined (brand, card_type) winner per prefix fails whenever a new write supplies (None, "PREPAID") (which would accidentally erase "MASTERCARD") or when brand comes from a 6-digit prefix and card_type comes from an 8-digit prefix.
Let's walk through Example 2 on card "341299001122334":
1. store("34", "issuer_db", trust=50, brand="AMEX", type="CHARGE") -> winners["34"] = [(50,"AMEX"), (50,"CHARGE")]
2. store("3412", "partner_csv", trust=3, brand="AMEX_CORP", type=None) -> winners["3412"] = [(3,"AMEX_CORP"), None]
3. store("3412", "manual_fix", trust=1, brand="WRONG_BRAND", type=None) -> trust 1 < 3 (ignored!) -> winners["3412"] unchanged
4. lookup("341299001122334") probes sorted_lengths = [4, 2]:
- L = 4 ("3412"): fills resolved_brand = "AMEX_CORP" (even at trust 3, length 4 beats trust 50 at length 2!)
- L = 2 ("34"): resolved_brand already set; fills missing resolved_type = "CHARGE"
-> returns ("AMEX_CORP", "CHARGE")
Complexity
Let N be len(operations), P <= 32 be the maximum prefix length, D <= 32 be the number of distinct stored prefix lengths, and U be the number of distinct stored prefixes (U <= N).
storeoperation:O(P)average time. Hashingprefix(length<= P) forprefix_winners.get(prefix)and updating two tuple slots takeO(P)time. Inserting a newly seen prefix length and sortingsorted_lengthshappens at most32times across the entire run (<= 32 * log2(32)comparisons total), adding negligibleO(1)amortized overhead.lookupoperation:O(D * P)average time (bounded by a small constant<= 32 * 32 = 1,024character steps)._lookup_cardchecks at mostDdistinct prefix lengths from longest to shortest, slicing and hashingcard_number[:prefix_len](O(P)) per probe and stopping early as soon as bothbrandandcard_typeare resolved (for standard6- and8-digit BINs,D = 2).- Overall run:
O(N * D * P)time. Every one of theNoperations runs in bounded constant time with respect toNandU, easily handling200,000operations in well under half a second in Python. - Space:
O(U * P).prefix_winnersstores one key of length<= Pand a two-slot list per distinct prefixU, so repeated writes to existing prefixes allocate zero additional table entries.
Edge cases
- Lookup before any store, no matching prefix, or empty
card_number = "":_lookup_cardfinds no matches and returns(None, None). card_numbershorter than a stored prefix (e.g., card"12345"vs. prefix"123456"):if prefix_len > card_len: continueskips"123456"cleanly; without this guard,card_number[:6]in Python silently evaluates to"12345"and could falsely match a5-digit prefix on the wrong iteration!card_numberexactly equal to a stored prefix:prefix_len == card_lenpassesprefix_len > card_len, andcard_number[:card_len]matches the exact prefix as required.- Negative or zero
trustvalues (e.g.,trust = -2): Because empty slots start asNonerather than0or-1, negative trust scores are stored and compared accurately. - Repeated identical write (
same prefix, source, trust, and values): Treated as a brand-new arrival, sotrust >= current_winner[0]updates the slot and makes that value the most recent winner over any intervening equal-trust write. - Only one field matched across all prefixes: Returns
(resolved_brand, None)or(None, resolved_type)cleanly.
Common mistakes
- Storing one winner per prefix instead of one winner per
(prefix, field): Breaks whenever a write setsbrand = None, card_type = "DEBIT"(either erasing the old brand or dropping the new card type) or whenbrandandcard_typehave different winning writes at the same prefix. - Using strict
>instead of>=when comparingtrust:trust > current_winner[0]keeps the first write on trust ties, violating Rule 4 (most recent write wins ties). - Comparing
trustacross different prefix lengths: Atrust = 1write on an8-digit prefix must beat atrust = 100write on a6-digit prefix for every field the8-digit write supplied; length always comes first. - Skipping
if prefix_len > len(card_number): continue: Because Python slicing clamps"123"[:6]to"123", forgetting the length check causes a probe for length6to accidentally look up a3-digit prefix out of order (though longest-first order happens to visit6before3, checkingprefix_len > card_lenavoids wasted hashes and duplicate lookups). - Pre-loading all
"store"operations before running"lookup"operations: Violates online stream ordering when stores and lookups are interleaved.
Alternative approaches
- Digit trie (prefix tree): A trie is a tree where each edge represents one digit
0–9and each node stores[brand_winner, type_winner]for the prefix ending at that node; a lookup walksmin(len(card_number), 32)characters from the root and remembers the deepest non-Nonebrand and deepest non-Nonecard type inO(min(len(card_number), P))character steps without string slicing. When many different prefix lengths (1..32) are populated simultaneously, a trie avoids hashing up to32slices; when only2–3lengths exist (such as6and8), hash-probingsorted_lengthsis shorter and often faster in CPython because dict hashing runs in C. - Sorted non-overlapping intervals with binary search: Production payment switches sometimes distribute BIN tables as numeric ranges (
41111100–41111199) rather than single prefixes; decomposing overlapping ranges into disjoint intervals and querying withbisectresolves lookups inO(log M)time forMranges.
Follow-up questions
- What changes are needed if individual writes can be deleted or an entire data source is revoked? Once writes can be removed, keeping only the top winner per slot is no longer enough because deleting the winner must promote the runner-up. Store a max-heap of
(trust, arrival_seq, write_id, value, source)per(prefix, field)along with arevoked_sourcesset (ordeleted_write_idsset), and lazily pop any heap top whosesourceorwrite_idhas been revoked whenever that slot is read during_lookup_card. - How would you scale concurrent reads across many threads in a read-heavy workload? Use copy-on-write snapshot swapping (or Read-Copy-Update / RCU): readers grab a single reference to an immutable
(prefix_winners, sorted_lengths)snapshot without acquiring any lock, while a single writer batches updates onto a copy (or persistent hash-array mapped trie) and atomically swaps the snapshot reference. When memory is too large to copy per batch, shard or guard the table with a reader-writer lock biased toward readers. - Why can overwritten records at a prefix be safely discarded when writes are append-only? Define the priority of write
wat prefixpfor fieldfaskey(w) = (w.trust, w.arrival_seq), which forms a strict total order becausearrival_seqis unique. If writew1is present whenw2arrives (or vice versa) andkey(w1) < key(w2),w2remains at prefixpforever unless replaced by somew3withkey(w2) < key(w3), so by transitivity (key(w1) < key(w2) < key(w3))w1can never hold the maximum key at prefixpat any future point in time.
Follow-up questions
- What changes are needed if individual writes can be deleted or an entire data source is revoked?
- How would you scale concurrent reads across many threads in a read-heavy workload?
- Why can overwritten records at a prefix be safely discarded when writes are append-only?
Similar questions
- Dynamic Customer Payment Network Queries
- Find Valid 2x2 Subgrids Containing Each Marked Cell
- Walking Through a Production Project With Defensible AI Use
- Driving a High-Impact Migration Across Legacy and Regulated Systems
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger