Filter Financial Logs by Active Premium Periods
Greedy & IntervalsAuto-graded · 13 test casesLast updated
Filter a chronological sequence of transaction records based on whether they fall within active premium membership intervals.
Given a list of transaction records transactions and a list of subscription records memberships, extract and return all transactions that occurred while the corresponding user held an active "golden" tier subscription.
Each record in transactions is a dictionary containing:
"trans_id": Unique integer identifier for the transaction."user_id": Integer identifier for the user."trans_date": Date string formatted as"YYYY-MM-DD"."amount": Numeric transaction amount.
Each record in memberships is a dictionary containing:
"user_id": Integer identifier for the user."tier": Subscription level (e.g.,"golden","silver")."start_date": Date string formatted as"YYYY-MM-DD"marking the start of the tier interval."end_date": Date string formatted as"YYYY-MM-DD"marking the end of the tier interval, orNoneif the subscription is still ongoing.
A transaction is considered to take place during a "golden" subscription period if:
- The user's tier is
"golden". start_date <= trans_date.end_dateisNoneortrans_date <= end_date.
Both start and end dates are inclusive boundaries.
Input Constraints
- Each string date is formatted strictly as
"YYYY-MM-DD", allowing standard string comparison operations to determine temporal ordering. - A user may have zero, one, or multiple membership records.
- Output records must preserve their original relative order from
transactions. - If a transaction matches multiple overlapping
"golden"periods for the same user, it should only appear once in the output.
Constraints
- $1 \le \text{len(transactions)} \le 5000$
- $1 \le \text{len(memberships)} \le 5000$
Examples
Example 1
Input: transactions_during_golden_membership([{'trans_id': 1, 'user_id': 101, 'trans_date': '2023-01-05', 'amount': 200}, {'trans_id': 2, 'user_id': 102, 'trans_date': '2023-01-07', 'amount': 150.5}, {'trans_id': 3, 'user_id': 101, 'trans_date': '2023-02-03', 'amount': 75}, {'trans_id': 4, 'user_id': 103, 'trans_date': '2023-02-10', 'amount': 50}], [{'user_id': 101, 'tier': 'golden', 'start_date': '2022-12-15', 'end_date': None}, {'user_id': 102, 'tier': 'silver', 'start_date': '2023-01-01', 'end_date': '2023-02-01'}, {'user_id': 103, 'tier': 'golden', 'start_date': '2023-02-01', 'end_date': '2023-03-01'}, {'user_id': 104, 'tier': 'golden', 'start_date': '2023-01-20', 'end_date': None}])
Output: [{'trans_id': 1, 'user_id': 101, 'trans_date': '2023-01-05', 'amount': 200}, {'trans_id': 3, 'user_id': 101, 'trans_date': '2023-02-03', 'amount': 75}, {'trans_id': 4, 'user_id': 103, 'trans_date': '2023-02-10', 'amount': 50}]
Hints
Hint 1
Map each user_id to a list of valid (start_date, end_date) ranges where tier == 'golden'.
Hint 2
String comparisons using standard ordering operators (<=, >=) work directly on 'YYYY-MM-DD' formatted strings.
Hint 3
Ensure that if end_date is None, the transaction is valid as long as it occurs on or after start_date.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task requires evaluating each transaction against a list of valid subscription windows for a specific user and subscription tier.
-
Pre-processing Subscriptions: Build a dictionary mapping each
user_idto a list of(start_date, end_date)tuples. Include only membership entries wheretier == "golden". -
Filtering Transactions: Iterate through
transactions. For each transaction, extract itsuser_idandtrans_date. Check if there exists at least one golden interval(start_date, end_date)for that user where:start_date <= trans_dateend_date is NoneORtrans_date <= end_date
Because standard ISO-8601 date strings (
"YYYY-MM-DD") preserve chronological order under standard lexicographical comparisons, we can directly compare the string values using<,<=,>,>=. -
Preserving Order & Uniqueness: Iterating over transactions sequentially guarantees the original order is preserved. Checking for any valid interval using
any()ensures a transaction is added at most once even if intervals overlap.
Complexity Analysis
- Time Complexity: $\mathcal{O}(M + T \cdot K)$, where $M$ is the number of membership records, $T$ is the number of transactions, and $K$ is the maximum number of golden intervals per user. Since $K$ is typically small, this simplifies to $\mathcal{O}(M + T)$.
- Space Complexity: $\mathcal{O}(M)$ auxiliary space to store the golden interval lookup table.
Python Reference Solution
from typing import Dict, List
def transactions_during_golden_membership(transactions: List[Dict], memberships: List[Dict]) -> List[Dict]:
golden_intervals = {}
for entry in memberships:
if entry["tier"] == "golden":
user = entry["user_id"]
if user not in golden_intervals:
golden_intervals[user] = []
golden_intervals[user].append((entry["start_date"], entry["end_date"]))
filtered = []
for tx in transactions:
u_id = tx["user_id"]
t_date = tx["trans_date"]
intervals = golden_intervals.get(u_id, [])
if any(s_date <= t_date and (e_date is None or t_date <= e_date) for s_date, e_date in intervals):
filtered.append(tx)
return filtered