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 string prefix, tagged with feed identifier source (str) and reliability score trust (int). At least one of brand or card_type is a non-None string; an omitted attribute is passed as None. Every "store" entry counts as a fresh arrival even if prefix, source, trust, and attribute values match a prior write.
  • ("lookup", card_number) — resolves (brand, card_type) for the digit string card_number using only "store" entries processed earlier in operations.

During a "lookup", evaluate brand and card_type separately using the following precedence order:

  1. Candidate filter: Keep only prior writes whose prefix is a leading prefix of card_number (card_number.startswith(prefix)) and whose value for the attribute being resolved is not None.
  2. Specificity first: Choose writes with the greatest len(prefix), even when a shorter matching prefix carries a higher trust score.
  3. Reliability tie-breaker: Among writes sharing that longest matching prefix, choose those with the largest trust value.
  4. Recency tie-breaker: If multiple writes at that prefix tie on trust, choose the write that appeared latest in operations.

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,000
  • 1 <= len(prefix) <= 32, consisting solely of ASCII digits '0'–'9'.
  • 0 <= len(card_number) <= 64, consisting solely of ASCII digits '0'–'9'.
  • trust is an arbitrary Python integer (negative, zero, or positive).
  • Every "store" operation provides at least one non-None value among brand and card_type.
  • source is retained as write metadata; multiple writes may share the same source or attribute values.
  • All operation tuples are well-formed; input validation is unnecessary.

Step-by-step walkthrough

  1. 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 6 digits, and often the first 8 digits in modern card ranges). Different data feeds report card attributes (brand such as "VISA" and card_type such as "DEBIT") at different prefix lengths and with different trust scores.

    When looking up a card_number, we resolve brand and card_type completely independently using three tie-breakers in strict priority order:

    1. Longest matching prefix first: Among all stored prefixes that start card_number and provided a non-None value for that field, pick the longest prefix — even if a shorter prefix has much higher trust!
    2. Highest trust at that prefix: If several writes targeted that exact same winning prefix, pick the one with the largest integer trust.
    3. Most recent write on trust ties: If two writes at that prefix share the highest trust, pick whichever arrived later in operations (even if its source and values repeat an earlier write).

    Let's also note the edge-case rules up front: - A None field means "not provided by this write" — it never deletes or overwrites an older value for that field. - A prefix equal in length to the entire card_number is a valid match; a prefix longer than card_number cannot match. - Operations are processed strictly in order, so a "lookup" sees only "store" operations that came before it.

  2. 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 list writes along with its arrival index, 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 W writes seen so far (O(W)). With 200,000 operations — say 100,000 stores followed by 100,000 lookups — that performs 100,000 * 100,000 = 10^10 prefix checks, taking minutes instead of milliseconds!

  3. Key idea 1: collapse all writes at one prefix into two winner slots

    Focus on a single prefix (say "520010") and one field (say brand). 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 process operations in chronological order, every incoming write automatically has a larger arrival_index than 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!

  4. Key idea 2: probe distinct stored lengths from longest to shortest

    Now how do we find the longest matching prefix of card_number without scanning every key in prefix_winners?

    Look at the constraint 1 <= len(prefix) <= 32. A card_number can 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 lengths L that 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_lengths runs strictly from longest to shortest, the very first matching prefix with a non-None brand is guaranteed to be the longest matching prefix for brand — and likewise independently for card_type!

  5. Code the per-slot store helper

    Let's write _update_slot and the "store" branch. We retain source inside the Winner = (trust, value, source) tuple as write metadata, and maintain seen_lengths alongside sorted_lengths so sorted_lengths.sort(reverse=True) runs at most 32 times across the entire 200,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)
    
  6. Code the longest-prefix lookup helper

    In _lookup_card, we skip any prefix_len > len(card_number) (since a prefix longer than the card number cannot match), look up card_number[:prefix_len] in prefix_winners in O(1) hash-table time, fill whichever of resolved_brand or resolved_type is still None, and break as 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)
    
  7. Trace Example 1 step by step

    Let's trace how the 6-digit prefix "520010" and 8-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" with trust = 8 at "520010", "5200108812345678" still gets "PREPAID" from "52001088" (trust = 2) because longest prefix (8 > 6) always wins before trust is compared.

  8. 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).

  • store operation: O(P) average time. Hashing prefix (length <= P) for prefix_winners.get(prefix) and updating two tuple slots take O(P) time. Inserting a newly seen prefix length and sorting sorted_lengths happens at most 32 times across the entire run (<= 32 * log2(32) comparisons total), adding negligible O(1) amortized overhead.
  • lookup operation: O(D * P) average time (bounded by a small constant <= 32 * 32 = 1,024 character steps). _lookup_card checks at most D distinct prefix lengths from longest to shortest, slicing and hashing card_number[:prefix_len] (O(P)) per probe and stopping early as soon as both brand and card_type are resolved (for standard 6- and 8-digit BINs, D = 2).
  • Overall run: O(N * D * P) time. Every one of the N operations runs in bounded constant time with respect to N and U, easily handling 200,000 operations in well under half a second in Python.
  • Space: O(U * P). prefix_winners stores one key of length <= P and a two-slot list per distinct prefix U, 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_card finds no matches and returns (None, None).
  • card_number shorter than a stored prefix (e.g., card "12345" vs. prefix "123456"): if prefix_len > card_len: continue skips "123456" cleanly; without this guard, card_number[:6] in Python silently evaluates to "12345" and could falsely match a 5-digit prefix on the wrong iteration!
  • card_number exactly equal to a stored prefix: prefix_len == card_len passes prefix_len > card_len, and card_number[:card_len] matches the exact prefix as required.
  • Negative or zero trust values (e.g., trust = -2): Because empty slots start as None rather than 0 or -1, negative trust scores are stored and compared accurately.
  • Repeated identical write (same prefix, source, trust, and values): Treated as a brand-new arrival, so trust >= 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 sets brand = None, card_type = "DEBIT" (either erasing the old brand or dropping the new card type) or when brand and card_type have different winning writes at the same prefix.
  • Using strict > instead of >= when comparing trust: trust > current_winner[0] keeps the first write on trust ties, violating Rule 4 (most recent write wins ties).
  • Comparing trust across different prefix lengths: A trust = 1 write on an 8-digit prefix must beat a trust = 100 write on a 6-digit prefix for every field the 8-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 length 6 to accidentally look up a 3-digit prefix out of order (though longest-first order happens to visit 6 before 3, checking prefix_len > card_len avoids 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–9 and each node stores [brand_winner, type_winner] for the prefix ending at that node; a lookup walks min(len(card_number), 32) characters from the root and remembers the deepest non-None brand and deepest non-None card type in O(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 to 32 slices; when only 2–3 lengths exist (such as 6 and 8), hash-probing sorted_lengths is 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 with bisect resolves lookups in O(log M) time for M ranges.

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 a revoked_sources set (or deleted_write_ids set), and lazily pop any heap top whose source or write_id has 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 w at prefix p for field f as key(w) = (w.trust, w.arrival_seq), which forms a strict total order because arrival_seq is unique. If write w1 is present when w2 arrives (or vice versa) and key(w1) < key(w2), w2 remains at prefix p forever unless replaced by some w3 with key(w2) < key(w3), so by transitivity (key(w1) < key(w2) < key(w3)) w1 can never hold the maximum key at prefix p at any future point in time.

Follow-up questions

Similar questions

More Square interview questions

All 5 Square questions →