Loading...
Loading...
You are building a fraud detection system for a financial platform. As transactions arrive one by one in a stream, your system must flag any transaction as anomalous if its amount is significantly higher than recent activity for that account.
Specifically, a transaction is considered anomalous if its amount is strictly greater than k times the median of the last w transactions for that account (not including the current transaction). If an account has fewer than w prior transactions, use all available prior transactions to compute the median. If an account has no prior transactions, the transaction is not anomalous.
Function Signature:
def detect_anomalies(transactions: List[Tuple[str, float]], w: int, k: float) -> List[bool]
Input:
transactions: A list of tuples (account_id, amount) representing the stream of transactions in chronological order.w: The sliding window size (number of prior transactions to consider).k: The multiplier threshold.Output:
transactions, where True means the corresponding transaction is anomalous.Input: transactions = [("A", 10), ("A", 12), ("A", 11), ("A", 100)], w = 3, k = 3
Output: [false, false, false, true]
Explanation:
Input: transactions = [("A", 5), ("B", 200), ("A", 6), ("B", 201), ("A", 500)], w = 2, k = 2
Output: [false, false, false, false, true]
Explanation:
1 <= transactions.length <= 10^4 1 <= w <= 10^3 1 <= k <= 100 0 < amount <= 10^9 account_id consists of alphanumeric characters, length 1-20 Median of even-length list = average of the two middle elements
Input: transactions = [("X", 1000)], w = 5, k = 1.5
Output: [false]
Explanation: No prior transactions for account X, so it cannot be anomalous.
w amounts, sort them, and compute the median. Consider using a sorted container (e.g., SortedList) for O(log n) insertions and O(1) median access.w were very large.