Score Multi-Product Borrowers Across Two Daily Logs

Medium · Data Manipulation (SQL/Python) · Software Engineer · Technical Screen

Problem Statement

Implement a log-processing pipeline that identifies repeat borrowers who use multiple loan products across two consecutive daily transaction feeds and ranks them with a caller-supplied scoring function.

You receive two transaction lists, day1_logs and day2_logs, together with a scoring callback trust_policy. Every entry in either list is a dictionary with four keys:

  • user_id (str): Borrower account identifier.
  • loan_id (str): Transaction identifier (unique across records).
  • loan_type (str): Product category label (such as "term_loan", "split_4", or "credit_line").
  • amount (float): Loan principal value.

A borrower qualifies for scoring when both criteria hold:

  1. At least one transaction for user_id exists in day1_logs and at least one exists in day2_logs.
  2. Combining that borrower's records across both days yields at least 2 unique loan_type strings.

For each qualifying borrower (and never for disqualified borrowers), assemble a summary dictionary and pass it to trust_policy(profile) -> float:

  • user_id (str): Borrower identifier.
  • distinct_loan_types (set[str]): All unique loan_type labels seen for this borrower across Day 1 and Day 2.
  • total_amount (float): Exact sum of amount across both days for this borrower, rounded to 2 decimal places.
  • day1_tx_count (int): Count of records for this borrower in day1_logs.
  • day2_tx_count (int): Count of records for this borrower in day2_logs.
from typing import List, Dict, Any, Callable

def evaluate_returning_borrowers(
    day1_logs: List[Dict[str, Any]],
    day2_logs: List[Dict[str, Any]],
    trust_policy: Callable[[Dict[str, Any]], float]
) -> List[Dict[str, Any]]:
    ...

Return a list of dictionaries—one per qualifying borrower—each containing strictly the three keys user_id, trust_score, and total_amount (where trust_score is the float returned by trust_policy(profile)). Order the output from highest trust_score to lowest, resolving equal scores by user_id in ascending lexicographical order ("a" before "b").

Examples

Example 1

day1_logs = [
    {"user_id": "acct_maya", "loan_id": "tx_101", "loan_type": "term_loan", "amount": 400.0},
    {"user_id": "acct_noah", "loan_id": "tx_102", "loan_type": "split_4", "amount": 80.0},
    {"user_id": "acct_omar", "loan_id": "tx_103", "loan_type": "term_loan", "amount": 150.0},
]
day2_logs = [
    {"user_id": "acct_maya", "loan_id": "tx_201", "loan_type": "split_4", "amount": 120.0},
    {"user_id": "acct_noah", "loan_id": "tx_202", "loan_type": "split_4", "amount": 60.0},
]

def demo_policy(profile: Dict[str, Any]) -> float:
    return round(len(profile["distinct_loan_types"]) * 15.0 + profile["total_amount"] * 0.05, 2)

evaluate_returning_borrowers(day1_logs, day2_logs, demo_policy)
# -> [{"user_id": "acct_maya", "trust_score": 56.0, "total_amount": 520.0}]

Walk-through: acct_omar has no Day 2 activity and is filtered out. acct_noah borrows on both days, yet uses "split_4" exclusively (1 unique product), so acct_noah is also filtered out. acct_maya borrows on both days across 2 unique products ("term_loan" and "split_4") with total_amount = 400.0 + 120.0 = 520.0, producing trust_score = 2 * 15.0 + 520.0 * 0.05 = 56.0.

Example 2

day1_logs = [
    {"user_id": "acct_zoe", "loan_id": "tx_301", "loan_type": "split_4", "amount": 90.0},
    {"user_id": "acct_zoe", "loan_id": "tx_302", "loan_type": "credit_line", "amount": 110.0},
    {"user_id": "acct_ava", "loan_id": "tx_303", "loan_type": "term_loan", "amount": 150.0},
]
day2_logs = [
    {"user_id": "acct_zoe", "loan_id": "tx_401", "loan_type": "split_4", "amount": 50.0},
    {"user_id": "acct_ava", "loan_id": "tx_402", "loan_type": "credit_line", "amount": 100.0},
]

def flat_tier_policy(profile: Dict[str, Any]) -> float:
    return float(len(profile["distinct_loan_types"]) * 20)

evaluate_returning_borrowers(day1_logs, day2_logs, flat_tier_policy)
# -> [
#     {"user_id": "acct_ava", "trust_score": 40.0, "total_amount": 250.0},
#     {"user_id": "acct_zoe", "trust_score": 40.0, "total_amount": 250.0},
# ]

Walk-through: acct_zoe already reaches 2 unique loan products on Day 1 and returns on Day 2 (day1_tx_count = 2, day2_tx_count = 1, total_amount = 250.0), so acct_zoe qualifies even though Day 2 repeats "split_4". acct_ava also qualifies (total_amount = 250.0). Both receive trust_score = 40.0, so "acct_ava" sorts ahead of "acct_zoe" alphabetically.

Constraints

  • 0 <= len(day1_logs), len(day2_logs) <= 100,000
  • 0.01 <= amount <= 50,000.0 (positive float values; guard against binary floating-point accumulation drift before rounding total_amount to 2 decimal places).
  • Every log dictionary has a unique loan_id.
  • Either input list (or both) can be empty.
  • Grouping and eligibility filtering must run in O(N + M) expected time for N = len(day1_logs) and M = len(day2_logs), followed by O(K log K) sorting over the K qualifying borrowers (assuming O(1) per trust_policy call).

Step-by-step walkthrough

  1. Understand the eligibility rules and output shape

    We receive two daily lists of loan transaction dictionaries (day1_logs and day2_logs) along with a plug-in scoring function trust_policy(profile) -> float. Each transaction has four fields: user_id, loan_id, loan_type, and amount.

    A borrower is eligible if and only if both conditions hold:

    1. Returning across consecutive days: at least 1 transaction in day1_logs and at least 1 transaction in day2_logs.
    2. Product diversity: at least 2 distinct loan_type values across all of their Day 1 and Day 2 records combined.

    Watch out for two subtle cases right away:

    Borrower    Day 1 loan_types              Day 2 loan_types   Distinct union                 Qualifies?
    ----------  ----------------------------  -----------------  -----------------------------  ----------
    acct_zoe    ["split_4", "credit_line"]    ["split_4"]        {"split_4", "credit_line"}     YES (both days, 2 products overall)
    acct_noah   ["split_4"]                   ["split_4"]        {"split_4"}                    NO  (repeats of 1 product don't count)
    acct_omar   ["term_loan"]                 []                 {"term_loan"}                  NO  (missing from Day 2)
    

    For each eligible borrower, we build a 5-field profile, compute trust_score = trust_policy(profile), and return [{"user_id": ..., "trust_score": ..., "total_amount": ...}] sorted by trust_score descending and tied user_id ascending.

  2. Why the naive nested scan is too slow

    A beginner's first instinct is often to collect all unique user IDs and, for each user, scan day1_logs and day2_logs from start to finish to gather their transactions:

    Suppose len(day1_logs) = N = 100,000  and  len(day2_logs) = M = 100,000:
      Up to (N + M) = 200,000 unique users
      x scanning (N + M) = 200,000 records per user
      = 40,000,000,000 (~4 x 10^10) dictionary checks  -> seconds or minutes in Python!
    

    Instead of re-scanning the lists for every user, we want to touch each log record once. Grouping records in a hash map (a Python dict keyed by user_id) turns per-record lookup and update into O(1) expected work, dropping total aggregation time from O((N + M)^2) to O(N + M).

  3. Aggregate each day in one O(N) pass

    Should we throw Day 1 and Day 2 into a single dictionary or build one dictionary per day? Building one dictionary per day (day1_stats and day2_stats) keeps the code clean and bug-free:

    • Checking whether a borrower appeared on both days becomes a single if user_id not in day2_stats: key lookup.
    • day1_tx_count and day2_tx_count stay naturally separated without extra if day == 1 branches.
    • Storing loan_types in a Python set automatically collapses duplicate loan types on the same day.
    from typing import List, Dict, Any, Callable
    
    
    def aggregate_day(logs: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
        """Aggregate one day's transactions per user in a single O(len(logs)) pass."""
        # stats: maps user_id -> {"loan_types": set, "amounts": list, "tx_count": int}
        stats: Dict[str, Dict[str, Any]] = {}
        for record in logs:
            user_id = record["user_id"]
            if user_id not in stats:
                stats[user_id] = {
                    "loan_types": set(),
                    "amounts": [],
                    "tx_count": 0,
                }
            user_entry = stats[user_id]
            user_entry["loan_types"].add(record["loan_type"])
            user_entry["amounts"].append(record["amount"])
            user_entry["tx_count"] += 1
        return stats
    
  4. Sum loan amounts accurately and build the borrower profile

    Once a user_id appears in both day1_stats and day2_stats, we combine their loan categories with a set union: combined_loan_types = day1_entry["loan_types"] | day2_entry["loan_types"]. Only if len(combined_loan_types) >= 2 do we build the profile.

    Financial totals require care with floating-point arithmetic. Because computers store floats in base 2 rather than base 10, 0.1 + 0.2 + 0.3 evaluates to 0.6000000000000001, and a naive total += amount loop can even give slightly different last bits depending on transaction order. We solve both issues cleanly:

    1. math.fsum(...) tracks exact intermediate carries so the sum is accurate to the last bit and independent of log order.
    2. round(exact_total, 2) rounds the final sum to 2 decimal places as required by the specification (handling both float representation noise like 0.6000000000000001 -> 0.6 and sub-cent inputs like 1.234 + 2.345 = 3.579 -> 3.58).
    import math
    
    
    def build_profile(
        user_id: str,
        day1_entry: Dict[str, Any],
        day2_entry: Dict[str, Any],
        combined_loan_types: set,
    ) -> Dict[str, Any]:
        """Construct the borrower summary dictionary passed into trust_policy(profile)."""
        all_amounts = day1_entry["amounts"] + day2_entry["amounts"]
        exact_total = math.fsum(all_amounts)
        rounded_total = round(exact_total, 2)
        return {
            "user_id": user_id,
            "distinct_loan_types": combined_loan_types,
            "total_amount": rounded_total,
            "day1_tx_count": day1_entry["tx_count"],
            "day2_tx_count": day2_entry["tx_count"],
        }
    
  5. Decouple scoring and sort with a mixed-direction key

    Notice that evaluate_returning_borrowers never hardcodes a scoring formula — it calls the injected trust_policy(profile) function only for eligible borrowers. Keeping data aggregation separate from scoring policy means risk engineers can swap a heuristic formula for a machine-learning scorer without touching the log-processing code, and unit tests can pass a mock function to verify the exact profile passed in. We also read total_amount = profile["total_amount"] before calling trust_policy(profile) so even an external policy that mutates its input dictionary cannot corrupt our output.

    Finally, we need to sort results by trust_score descending, breaking ties by user_id ascending ("a" before "b"). Passing reverse=True on (score, user_id) would flip both fields and break ties backwards ("b" before "a"). Instead, we negate the numeric score in an ascending sort key:

    Suppose "a", "b", and "c" are tied at trust_score = 20.0, while "d" has trust_score = 35.0:
    
    Result row                   ranking_key = (-trust_score, user_id)   Sorted position
    ---------------------------  -------------------------------------   ---------------
    {"user_id": "d", score: 35}  (-35.0, "d")                            1st (most negative -score)
    {"user_id": "a", score: 20}  (-20.0, "a")                            2nd ("a" < "b" < "c")
    {"user_id": "b", score: 20}  (-20.0, "b")                            3rd
    {"user_id": "c", score: 20}  (-20.0, "c")                            4th
    
    def ranking_key(result: Dict[str, Any]) -> tuple:
        """Sort highest trust_score first (-score), breaking ties by user_id ascending."""
        return (-result["trust_score"], result["user_id"])
    
  6. Trace Example 1 step by step

    Let's trace Example 1 with demo_policy(p) = round(len(p["distinct_loan_types"]) * 15.0 + p["total_amount"] * 0.05, 2):

    Input logs:
      Day 1:  (acct_maya, tx_101, "term_loan", 400.0),
              (acct_noah, tx_102, "split_4",    80.0),
              (acct_omar, tx_103, "term_loan", 150.0)
      Day 2:  (acct_maya, tx_201, "split_4",   120.0),
              (acct_noah, tx_202, "split_4",    60.0)
    
    Phase 1 — per-day dictionaries:
      day1_stats = {
          "acct_maya": {"loan_types": {"term_loan"}, "amounts": [400.0], "tx_count": 1},
          "acct_noah": {"loan_types": {"split_4"},   "amounts": [80.0],  "tx_count": 1},
          "acct_omar": {"loan_types": {"term_loan"}, "amounts": [150.0], "tx_count": 1},
      }
      day2_stats = {
          "acct_maya": {"loan_types": {"split_4"},   "amounts": [120.0], "tx_count": 1},
          "acct_noah": {"loan_types": {"split_4"},   "amounts": [60.0],  "tx_count": 1},
      }
    
    Phase 2 & 3 — intersect, check diversity, build profile, and score:
      acct_maya -> in both days; types = {"term_loan"} | {"split_4"} (size 2 >= 2 -> QUALIFIES)
                   profile = {"user_id": "acct_maya", "distinct_loan_types": {"term_loan", "split_4"},
                              "total_amount": 520.0, "day1_tx_count": 1, "day2_tx_count": 1}
                   score   = 2 * 15.0 + 520.0 * 0.05 = 56.0
    
      acct_noah -> in both days; types = {"split_4"} | {"split_4"} = {"split_4"} (size 1 < 2 -> SKIPPED)
      acct_omar -> missing from day2_stats -> SKIPPED
    
    Phase 4 — sorted output:
      [{"user_id": "acct_maya", "trust_score": 56.0, "total_amount": 520.0}]
    
  7. Complete solution

    from typing import List, Dict, Any, Callable
    import math
    
    
    def aggregate_day(logs: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
        """Aggregate one day's transactions per user in a single O(len(logs)) pass."""
        # stats: maps user_id -> {
        #     "loan_types": set of str (e.g. {"term_loan", "split_4"}),
        #     "amounts": list of float (e.g. [400.0, 120.0]),
        #     "tx_count": int (number of transactions on this day),
        # }
        stats: Dict[str, Dict[str, Any]] = {}
        for record in logs:
            user_id = record["user_id"]
            if user_id not in stats:
                stats[user_id] = {
                    "loan_types": set(),
                    "amounts": [],
                    "tx_count": 0,
                }
            user_entry = stats[user_id]
            user_entry["loan_types"].add(record["loan_type"])
            user_entry["amounts"].append(record["amount"])
            user_entry["tx_count"] += 1
        return stats
    
    
    def build_profile(
        user_id: str,
        day1_entry: Dict[str, Any],
        day2_entry: Dict[str, Any],
        combined_loan_types: set,
    ) -> Dict[str, Any]:
        """Construct the borrower summary dictionary passed into trust_policy(profile)."""
        # math.fsum computes an exact floating-point sum so record order never changes the total,
        # and round(..., 2) eliminates binary float artifacts like 0.1 + 0.2 + 0.3 = 0.6000000000000001.
        all_amounts = day1_entry["amounts"] + day2_entry["amounts"]
        exact_total = math.fsum(all_amounts)
        rounded_total = round(exact_total, 2)
        return {
            "user_id": user_id,
            "distinct_loan_types": combined_loan_types,
            "total_amount": rounded_total,
            "day1_tx_count": day1_entry["tx_count"],
            "day2_tx_count": day2_entry["tx_count"],
        }
    
    
    def ranking_key(result: Dict[str, Any]) -> tuple:
        """Sort highest trust_score first (-score), breaking ties by user_id ascending."""
        # Negating trust_score lets a single ascending sort order scores high-to-low while
        # keeping user_id in A-to-Z lexicographical order (unlike reverse=True, which flips both).
        return (-result["trust_score"], result["user_id"])
    
    
    def evaluate_returning_borrowers(
        day1_logs: List[Dict[str, Any]],
        day2_logs: List[Dict[str, Any]],
        trust_policy: Callable[[Dict[str, Any]], float]
    ) -> List[Dict[str, Any]]:
        # Phase 1: summarize each day independently in O(N + M) expected time.
        day1_stats = aggregate_day(day1_logs)
        day2_stats = aggregate_day(day2_logs)
    
        # Phase 2: filter to borrowers active on BOTH days with >= 2 distinct loan types overall.
        # results: list of {"user_id": str, "trust_score": float, "total_amount": float}
        results: List[Dict[str, Any]] = []
        for user_id, day1_entry in day1_stats.items():
            if user_id not in day2_stats:
                continue
    
            day2_entry = day2_stats[user_id]
            # Set union combines distinct loan categories across Day 1 and Day 2 together.
            combined_loan_types = day1_entry["loan_types"] | day2_entry["loan_types"]
            if len(combined_loan_types) < 2:
                continue
    
            # Phase 3: build the profile, save total_amount before calling the external policy,
            # and score only eligible borrowers.
            profile = build_profile(user_id, day1_entry, day2_entry, combined_loan_types)
            total_amount = profile["total_amount"]
            score = trust_policy(profile)
            results.append({
                "user_id": user_id,
                "trust_score": score,
                "total_amount": total_amount,
            })
    
        # Phase 4: sort the K eligible borrowers in O(K log K) time.
        results.sort(key=ranking_key)
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a lending clerk reviewing Monday's and Tuesday's paper receipt stacks to find loyal borrowers who use more than one credit product. Instead of picking one customer's name and flipping through all 200,000 receipts from top to bottom over and over, the clerk makes one pass through Monday's stack to jot down a mini-folder per customer (products used, dollar amounts, receipt count), makes one pass through Tuesday's stack to do the same, and then checks only customers who have a folder on both days and at least two unique loan types across their two folders combined. Each qualifying folder is handed to a separate scoring rulebook (trust_policy), and the winning summaries are sorted from highest score to lowest.

The naive approach — looping over every unique user_id and scanning day1_logs and day2_logs inside the loop — takes O((N + M)^2) time, reaching tens of billions of operations when N = M = 100,000. Beginners also get tripped up by floating-point arithmetic (0.1 + 0.2 + 0.3 produces 0.6000000000000001 in standard binary floats) and by sorting with reverse=True, which accidentally reverses alphabetical tie-breaking on user_id.

Walk through Example 1 (acct_maya takes a 400.0 "term_loan" on Day 1 and a 120.0 "split_4" loan on Day 2; acct_noah takes "split_4" loans of 80.0 and 60.0 on Days 1 and 2; acct_omar takes 150.0 on Day 1 only): 1. Per-day hash maps: day1_stats records acct_maya ({"term_loan"}, [400.0], count 1), acct_noah ({"split_4"}, [80.0], count 1), and acct_omar; day2_stats records acct_maya ({"split_4"}, [120.0], count 1) and acct_noah ({"split_4"}, [60.0], count 1). 2. Intersection & diversity check: acct_omar is absent from day2_stats. Both acct_maya and acct_noah appear on both days, and taking the set union (combining two sets while discarding duplicates) gives acct_maya {"term_loan", "split_4"} (size 2 >= 2, qualifies) and acct_noah {"split_4"} (size 1 < 2, excluded). 3. Profile & scoring: acct_maya gets total_amount = round(fsum([400.0, 120.0]), 2) = 520.0 and trust_score = 2 * 15.0 + 520.0 * 0.05 = 56.0, returning [{"user_id": "acct_maya", "trust_score": 56.0, "total_amount": 520.0}].

Complexity

Let N = len(day1_logs), M = len(day2_logs), U be the number of unique users, and K be the number of eligible returning borrowers (K <= min(N, M)).

  • Time — O(N + M + K log K) expected (assuming O(1) per trust_policy call):
    • Scanning day1_logs and day2_logs once performs one hash map (dictionary with O(1) average key lookup) operation, one set.add, and one list append per transaction, costing O(N + M) expected time.
    • Iterating through day1_stats checks user_id in day2_stats in O(1) average time per user; across all returning users, unioning loan_types sets and summing amounts with math.fsum visits at most N + M stored items in total (O(N + M)).
    • Calling trust_policy runs K times (once per eligible user), and sorting the K output dictionaries takes O(K log K) comparisons.
  • Space — O(N + M):
    • Storing per-user amounts lists and loan_types sets across both days holds at most N + M floats and N + M loan-type strings in memory. (If memory is tight and record-order-exact summation before rounding is not needed, accumulating a running total += amount float per user shrinks space to O(U * T) for U users and T distinct loan types.)

Edge cases

  • Empty day1_logs, empty day2_logs, or both empty: No user_id can exist in both dictionaries, so the loop finishes immediately, trust_policy is called 0 times, and [] is returned.
  • Multiple loans of the same type across both days: Three "term_loan" records across Day 1 and Day 2 collapse to a 1-element set {"term_loan"}, disqualifying the borrower.
  • All product diversity occurs on a single day: A borrower with "split_4" + "credit_line" on Day 1 and "split_4" again on Day 2 still has union size 2 and does qualify, because diversity is defined across combined records from both days.
  • IEEE-754 floating-point drift and sub-cent amounts: IEEE-754 floating-point drift (tiny rounding errors caused by storing base-10 decimals in base-2 binary floats) turns 0.1 + 0.2 + 0.3 into 0.6000000000000001; math.fsum followed by round(..., 2) returns exact 0.6, and sums like 1.234 + 2.345 = 3.579 round cleanly to 3.58.
  • Tied trust_score values: Ties sort in ascending lexicographical order ("a" before "b", "u10" before "u2"), handled cleanly by (-result["trust_score"], result["user_id"]).
  • External trust_policy mutating its input dict: Saving total_amount = profile["total_amount"] before invoking trust_policy(profile) protects the output row even if a caller's policy modifies profile in place.

Common mistakes

  • Checking len(day1_types) >= 2 and len(day2_types) >= 2 or requiring Day 2's type to differ from Day 1's: Disqualifies a valid borrower who took two loan types on Day 1 and returned with one of those types on Day 2.
  • Scanning day2_logs as a list (any(r["user_id"] == u for r in day2_logs)) inside a loop: Turns an O(N + M) pass into an O(N * M) bottleneck (~10^10 checks at 100,000 logs/day).
  • Sorting with results.sort(key=lambda r: (r["trust_score"], r["user_id"]), reverse=True): reverse=True inverts both tuple elements, breaking ties by user_id descending ("c", "b", "a") instead of ascending ("a", "b", "c").
  • Rounding individual transactions before summing, or rounding trust_score: Rounding per transaction accumulates cent errors on fractional fees (1.234 + 2.345 rounded early gives 1.23 + 2.35 = 3.58, whereas 1.004 + 1.004 gives 2.00 instead of 2.01), and the specification leaves trust_score rounding strictly up to trust_policy.
  • Calling trust_policy before filtering out ineligible users: Wastes compute (especially when trust_policy calls an ML model or external service) and breaks tests verifying that only eligible profiles reach the policy.
  • Returning extra profile fields in the final output: Each output dictionary must contain only user_id, trust_score, and total_amount.

Alternative approaches

  • Single combined hash map with day flags: Maintain one dictionary keyed by user_id storing day1_tx_count, day2_tx_count, loan_types, and amounts, then filter with day1_tx_count >= 1 and day2_tx_count >= 1 and len(loan_types) >= 2. Asymptotically identical (O(N + M) time and space) with slightly fewer hash lookups when most users return, though two per-day maps keep aggregate_day completely reusable across any number of days.
  • Fixed-point Decimal arithmetic: Converting amounts via Decimal(str(amount)) performs exact base-10 arithmetic without binary float representation artifacts, at roughly 10–20x higher CPU cost per addition than math.fsum on native floats.

Follow-up questions

  • If each day's transaction feed grows beyond single-node RAM, how would you redesign this pipeline in SQL or Spark? Tag Day 1 rows with log_day = 1 and Day 2 rows with log_day = 2 via UNION ALL, then run a single distributed GROUP BY user_id (which hash-partitions records by user_id across cluster workers in one shuffle without any expensive raw-log join). Store monetary columns as exact DECIMAL(12, 2) and evaluate trust_policy as a vectorized UDF (or in Python on the filtered qualifying output, which is typically much smaller than raw logs):

sql SELECT user_id, COUNT(DISTINCT loan_type) AS distinct_type_count, ROUND(SUM(amount), 2) AS total_amount, SUM(CASE WHEN log_day = 1 THEN 1 ELSE 0 END) AS day1_tx_count, SUM(CASE WHEN log_day = 2 THEN 1 ELSE 0 END) AS day2_tx_count FROM ( SELECT 1 AS log_day, user_id, loan_type, amount FROM day1_logs UNION ALL SELECT 2 AS log_day, user_id, loan_type, amount FROM day2_logs ) AS combined_logs GROUP BY user_id HAVING SUM(CASE WHEN log_day = 1 THEN 1 ELSE 0 END) >= 1 AND SUM(CASE WHEN log_day = 2 THEN 1 ELSE 0 END) >= 1 AND COUNT(DISTINCT loan_type) >= 2;

  • What changes are needed if upstream retries produce duplicate loan_id records within or across the two daily feeds? Enforce idempotency (processing a retried event multiple times produces the exact same state as processing it once) by tracking seen loan_id strings in a seen_loan_ids set across Day 1 first and Day 2 second. If a loan_id from Day 1 reappears in Day 2 due to a retry across midnight, attributing it solely to its earliest timestamp prevents a single-day borrower from falsely qualifying as a two-day returning borrower; if a duplicate loan_id arrives with a different user_id or amount, flag or log a data-integrity anomaly rather than silently dropping it. In SQL or Spark, apply ROW_NUMBER() OVER (PARTITION BY loan_id ORDER BY event_timestamp ASC) = 1 before grouping by user_id.
  • Suppose the scoring callback needs 30-day rolling borrower metrics instead of just two days — how would you structure storage and pre-aggregation to stay fast? Avoid re-scanning 30 days of raw transaction logs on every run; instead maintain a daily rollup table (pre-aggregated summary rows keyed by (user_id, activity_date, loan_type) storing tx_count and amount_sum). A 30-day borrower profile then sums at most 30 * T tiny summary rows per user (for T loan types), or updates a sliding 30-day state in O(T) time by adding Day D and subtracting Day D - 30 — storing per-type integer counts ({"split_4": 4, "term_loan": 1}) rather than plain sets so a loan type is removed only when its 30-day count drops to zero, and serving precomputed profiles from a low-latency feature store (a key-value database of ready-to-use model/policy inputs keyed by user_id).

Follow-up questions

Similar questions

More Affirm interview questions

All 28 Affirm questions →