KatInterview

Build a Subscription Pattern Recognition Engine

Data Structure DesignModel answer
HardModel answerData Structure Designpattern-recognitiondata-processingheuristics

Last updated

Create a system that discovers recurring billing patterns in transaction data, handling merchant name variations, timing drift, and price changes.

Challenge

Financial platforms need to identify subscription charges automatically from raw transaction feeds. The challenge lies in messy real-world data: merchant names appear inconsistently (NETFLIX 8471 versus NETFLIX INC), billing dates shift due to weekends and month-length variations, and charges fluctuate when users upgrade plans or subscriptions adjust pricing.

Your task is to build a RecurringDetector class that processes a list of transactions and identifies subscription patterns, returning structured metadata about each discovered stream.

Core Requirements

Merchant Grouping: Create a normalization strategy to cluster transactions from the same vendor despite naming inconsistencies. Strip trailing reference codes, identifiers, and other variable suffixes to establish stable merchant identifiers.

Pattern Classification: Once grouped (requiring at least 3 occurrences), determine the billing frequency:

  • WEEKLY: Charges repeat roughly every 7 days (within t_days tolerance)
  • MONTHLY: Charges repeat roughly every 30 days (accepting 28–33 day range plus t_days tolerance)
  • ANNUAL: Charges repeat roughly every 365 days (accepting 360–370 day range plus t_days tolerance)

Amount Consistency: Charges should cluster around a central amount within t_amount_pct tolerance from the median. Allow for one discrete price change (such as a tier upgrade) but not ongoing volatility.

Noise Filtering: Remove duplicate charges—transactions from the same merchant with matching amounts posted within 24 hours (retain the earliest).

Transparency: Each identified subscription must include the normalized merchant name, frequency category, representative charge amount, predicted next billing date, and a confidence metric (0.0–1.0) reflecting pattern strength.

API Specification

from dataclasses import dataclass
from typing import List
from datetime import date

@dataclass
class Transaction:
    id: str
    description: str
    amount_cents: int
    date: str  # Format: "YYYY-MM-DD"

@dataclass
class RecurringStream:
    merchant: str
    cadence: str           # One of: "WEEKLY", "MONTHLY", "ANNUAL"
    typical_amount_cents: int
    next_expected_date: str
    confidence: float      # Range: 0.0 to 1.0
    transaction_ids: List[str]

class RecurringDetector:
    def __init__(self, t_days: int = 3, t_amount_pct: float = 0.15):
        """
        Parameters:
          t_days: Acceptable day variance from standard interval
          t_amount_pct: Acceptable proportional variance from median amount
        """
        pass

    def detect(self, transactions: List[Transaction]) -> List[RecurringStream]:
        """Returns list of detected recurring subscription patterns"""
        pass

Specifications

  • Input size: up to 100,000 transactions
  • Transactions may arrive unsorted
  • All amounts are positive integers in cents (1 to 100,000,000)
  • Target complexity: O(N log N) or better

Sample Usage

txs = [
    Transaction("1", "DROPBOX* 7XK9P2", 999, "2023-01-10"),
    Transaction("2", "DROPBOX INC", 999, "2023-02-10"),
    Transaction("3", "DROPBOX 9AK2", 999, "2023-03-11"),
    Transaction("4", "DROPBOX", 999, "2023-04-10"),
]
detector = RecurringDetector(t_days=3, t_amount_pct=0.10)
results = detector.detect(txs)
# Expected output includes:
# RecurringStream(
#   merchant="DROPBOX",
#   cadence="MONTHLY",
#   typical_amount_cents=999,
#   next_expected_date="2023-05-10",
#   confidence=0.93,
#   transaction_ids=["1","2","3","4"]
# )

Hints

Hint 1

Start by designing your merchant normalization logic—test it independently with various real merchant name formats before integrating

Hint 2

Use the median interval between charges rather than the mean to make cadence detection robust to occasional outliers

Hint 3

When checking amount consistency, look for at most one discontinuous jump that could represent a legitimate price change, then verify consistency within each price segment