Build a Subscription Pattern Recognition Engine
Data Structure DesignModel answerLast 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 (withint_daystolerance)MONTHLY: Charges repeat roughly every 30 days (accepting 28–33 day range plust_daystolerance)ANNUAL: Charges repeat roughly every 365 days (accepting 360–370 day range plust_daystolerance)
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
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
This problem requires building a robust pattern matcher that handles noisy financial data. The solution follows a multi-stage pipeline where each stage can be developed and tested independently.
Architecture Overview
The detector operates in four distinct phases:
Phase 1: Merchant Normalization and Grouping
Raw transaction descriptions must be mapped to canonical merchant identifiers. The normalization process:
- Convert to uppercase
- Handle payment processor prefixes (e.g.,
SQ *MERCHANTmeans the merchant name follows the asterisk) - For standard formats, truncate at the asterisk since processors append transaction IDs after it
- Tokenize on non-alphanumeric characters
- Remove trailing tokens that are clearly variable: sequences containing digits, US state codes, or corporate suffixes like
INC,LLC,CORP,TECHNOLOGIES,CO - Never remove the last remaining token
Examples:
DROPBOX* 7XK9P2→DROPBOXNETFLIX INC 441→NETFLIXSQ *LOCAL COFFEE→LOCAL COFFEE
After normalization, group all transactions by their canonical merchant key.
Phase 2: Temporal Sorting and Deduplication
For each merchant group:
- Sort transactions by date
- Scan for duplicates: if consecutive transactions have identical amounts and dates within 24 hours, keep only the first (this handles posting delays or processor retries)
Phase 3: Cadence Detection
Require at least 3 transactions post-deduplication. Compute day intervals between consecutive charges. The key insight is to use the median interval for classification, which is robust to a single anomalous gap.
Define acceptance windows:
WEEKLY: median in range[7 - t_days, 7 + t_days]MONTHLY: median in range[max(1, 28 - t_days), 33 + t_days](accounts for February and month-length variation)ANNUAL: median in range[max(1, 360 - t_days), 370 + t_days]
After classifying by median, verify that every individual gap falls within the chosen window. This prevents false positives where the median looks monthly but individual gaps are chaotic.
Phase 4: Amount Validation
Calculate the median charge amount. Check if all amounts fall within t_amount_pct of this median. If not, allow for one price tier change:
- Compute relative differences between consecutive amounts
- Find the largest relative jump
- Split the sequence at that point
- Verify each segment is internally consistent (all amounts within tolerance of that segment's median)
- If both segments pass, accept the stream; otherwise reject it
The "typical amount" for output is the median of the more recent price segment.
Phase 5: Metadata Generation
For each validated stream:
-
Merchant: The normalized key
-
Cadence: The classified frequency
-
Typical amount: Median of current price tier
-
Next expected date: Last transaction date plus median interval
-
Confidence: Combine three factors:
- Interval regularity: standard deviation of gaps relative to median (lower is better)
- Amount stability: how tightly amounts cluster (lower variance → higher confidence)
- History depth: more transactions → higher confidence (e.g.,
min(1.0, num_transactions / 6))
Final confidence =
(regularity_score * 0.4) + (amount_score * 0.3) + (history_score * 0.3)
Complexity Analysis
- Grouping by merchant: O(N × M) where M is average description length (effectively O(N) with short strings)
- Sorting each group: O(N log N) worst case if all transactions are from one merchant
- Interval and amount analysis: O(N) linear scans
- Overall: O(N log N)
Implementation Sketch
from collections import defaultdict
from datetime import datetime, timedelta
import statistics
class RecurringDetector:
def __init__(self, t_days=3, t_amount_pct=0.15):
self.t_days = t_days
self.t_amount_pct = t_amount_pct
self.corp_suffixes = {'INC', 'LLC', 'CORP', 'CO', 'LTD', 'TECHNOLOGIES'}
self.us_states = {'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL',
'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA',
'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE',
'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK',
'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT',
'VA', 'WA', 'WV', 'WI', 'WY', 'DC'}
def normalize_merchant(self, desc):
desc = desc.upper()
# Handle payment processor formats
if desc.startswith('SQ *') or desc.startswith('TST*') or desc.startswith('PAYPAL *'):
parts = desc.split('*', 1)
if len(parts) > 1:
desc = parts[1]
elif '*' in desc:
desc = desc.split('*')[0]
# Tokenize
tokens = []
current = []
for ch in desc:
if ch.isalnum():
current.append(ch)
else:
if current:
tokens.append(''.join(current))
current = []
if current:
tokens.append(''.join(current))
# Strip trailing noise
while len(tokens) > 1:
last = tokens[-1]
if any(c.isdigit() for c in last):
tokens.pop()
elif last in self.us_states or last in self.corp_suffixes:
tokens.pop()
else:
break
return ' '.join(tokens) if tokens else 'UNKNOWN'
def detect(self, transactions):
# Group by normalized merchant
groups = defaultdict(list)
for tx in transactions:
merchant = self.normalize_merchant(tx.description)
groups[merchant].append(tx)
results = []
for merchant, txs in groups.items():
if len(txs) < 3:
continue
# Sort and dedupe
txs_sorted = sorted(txs, key=lambda t: t.date)
deduped = [txs_sorted[0]]
for tx in txs_sorted[1:]:
prev = deduped[-1]
date_diff = (datetime.fromisoformat(tx.date) -
datetime.fromisoformat(prev.date)).days
if date_diff <= 1 and tx.amount_cents == prev.amount_cents:
continue
deduped.append(tx)
if len(deduped) < 3:
continue
# Compute intervals
intervals = []
for i in range(1, len(deduped)):
days = (datetime.fromisoformat(deduped[i].date) -
datetime.fromisoformat(deduped[i-1].date)).days
intervals.append(days)
median_interval = statistics.median(intervals)
# Classify cadence
cadence = None
expected_range = None
if 7 - self.t_days <= median_interval <= 7 + self.t_days:
cadence = 'WEEKLY'
expected_range = (7 - self.t_days, 7 + self.t_days)
elif 28 - self.t_days <= median_interval <= 33 + self.t_days:
cadence = 'MONTHLY'
expected_range = (28 - self.t_days, 33 + self.t_days)
elif 360 - self.t_days <= median_interval <= 370 + self.t_days:
cadence = 'ANNUAL'
expected_range = (360 - self.t_days, 370 + self.t_days)
else:
continue
# Verify all intervals fit
if not all(expected_range[0] <= iv <= expected_range[1] for iv in intervals):
continue
# Amount validation with step-change tolerance
amounts = [tx.amount_cents for tx in deduped]
median_amt = statistics.median(amounts)
threshold = median_amt * self.t_amount_pct
if not all(abs(amt - median_amt) <= threshold for amt in amounts):
# Try split at largest jump
jumps = [(abs(amounts[i] - amounts[i-1]) / amounts[i-1], i)
for i in range(1, len(amounts))]
if jumps:
_, split_idx = max(jumps)
seg1 = amounts[:split_idx]
seg2 = amounts[split_idx:]
med1 = statistics.median(seg1)
med2 = statistics.median(seg2)
valid1 = all(abs(a - med1) <= med1 * self.t_amount_pct for a in seg1)
valid2 = all(abs(a - med2) <= med2 * self.t_amount_pct for a in seg2)
if not (valid1 and valid2):
continue
median_amt = med2 # Use recent tier
# Calculate confidence
interval_std = statistics.stdev(intervals) if len(intervals) > 1 else 0
regularity = max(0, 1 - (interval_std / median_interval))
amount_std = statistics.stdev(amounts) if len(amounts) > 1 else 0
amount_stability = max(0, 1 - (amount_std / median_amt))
history_factor = min(1.0, len(deduped) / 6)
confidence = (regularity * 0.4 + amount_stability * 0.3 + history_factor * 0.3)
# Predict next date
last_date = datetime.fromisoformat(deduped[-1].date)
next_date = last_date + timedelta(days=int(median_interval))
results.append(RecurringStream(
merchant=merchant,
cadence=cadence,
typical_amount_cents=int(median_amt),
next_expected_date=next_date.strftime('%Y-%m-%d'),
confidence=round(confidence, 2),
transaction_ids=[tx.id for tx in deduped]
))
return results
Common Pitfalls
-
Using mean instead of median: A single late payment can skew the mean interval significantly, causing misclassification.
-
Ignoring month-length variation: Monthly subscriptions can range from 28 days (February) to 31 days legitimately.
-
Over-strict amount matching: Rejecting streams with any price variation misses legitimate tier upgrades. Allowing unlimited variation creates false positives.
-
Weak normalization: Failing to strip processor IDs and reference codes prevents grouping of related transactions.
-
Not validating individual gaps after median classification: The median might fall in range while individual intervals are erratic, producing false positives.
The key to a robust detector is balancing strictness (to avoid false positives) with flexibility (to handle real-world messiness). The median-based approach with bounded tolerance provides this balance effectively.