Flag Transactions That Exceed a Tier's Spending Threshold in a Rolling Time Window
Company: Square
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a fraud detection system that receives a stream of transactions and detects if a user has exceeded a specific spending threshold within a rolling time window.
The system supports different user tiers (`silver`, `gold`, `platinum`), each with its own spending threshold. When a transaction causes a user's total spending within the rolling window to exceed their tier's threshold, the transaction is flagged as fraudulent.
Users can be assigned or reassigned to tiers at any time. If a user has no tier assigned, they default to `silver`. Transactions that fall outside the rolling window are automatically excluded from the spending total. The tier thresholds are: `silver` = `1000.0`, `gold` = `5000.0`, `platinum` = `10000.0`.
The window length `windowSize` is given to the constructor, in the same units as the timestamps. The rolling window ending at time `T` contains the transactions whose timestamp `t` satisfies `T - windowSize < t <= T`.
Implement the following methods:
- `FraudDetector(windowSize: int)`: create a detector with the given window length.
- `setUserTier(userId: int, tier: str) -> None`: assign or reassign a user to a tier (`'silver'`, `'gold'` or `'platinum'`). This determines the spending threshold used for fraud detection.
- `addTransaction(userId: int, amount: float, timestamp: int) -> bool`: record a transaction for the given user. Return `True` if the user's total spending within the window ending at `timestamp`, including this transaction, exceeds their tier's threshold (flagged as fraudulent), otherwise `False`.
- `getSpending(userId: int, timestamp: int) -> float`: return the total spending for the given user within the rolling window ending at `timestamp`.
- `getUserTier(userId: int) -> str`: return the current tier of the user, or `'silver'` if no tier has been set.
```hint Keep the window total cheap
Summing a user's whole history on every call is linear in that history. Look for a per-user quantity you can maintain as transactions arrive.
```
```hint Read the getSpending contract closely
`getSpending` can ask about any timestamp, including one before the user's latest transaction. Check whether your eviction throws away data that such a query, or a later transaction, still needs.
```
### Examples
Example 1:
```text
Input:
["FraudDetector", "addTransaction", "addTransaction", "addTransaction", "getSpending", "addTransaction", "getSpending", "getUserTier"]
[[10], [1, 600.0, 1], [1, 300.0, 5], [1, 200.0, 8], [1, 8], [1, 100.0, 11], [1, 11], [1]]
Output: [null, false, false, true, 1100.0, false, 600.0, "silver"]
Explanation:
d = FraudDetector(10) # the window ending at T covers T-9 .. T
d.addTransaction(1, 600.0, 1) # -> False (window total 600.0, silver threshold 1000.0)
d.addTransaction(1, 300.0, 5) # -> False (900.0)
d.addTransaction(1, 200.0, 8) # -> True (1100.0 > 1000.0)
d.getSpending(1, 8) # -> 1100.0
d.addTransaction(1, 100.0, 11) # -> False (window 2 .. 11, the 600.0 at time 1 has expired: 300 + 200 + 100 = 600.0)
d.getSpending(1, 11) # -> 600.0
d.getUserTier(1) # -> "silver" (never set)
```
Example 2:
```text
Input:
["FraudDetector", "setUserTier", "addTransaction", "addTransaction", "setUserTier", "addTransaction", "getSpending", "getSpending", "getUserTier"]
[[100], [7, "gold"], [7, 3000.0, 10], [7, 2000.0, 20], [7, "silver"], [7, 50.0, 30], [7, 25], [7, 115], [8]]
Output: [null, null, false, false, null, true, 5000.0, 2050.0, "silver"]
Explanation:
d = FraudDetector(100)
d.setUserTier(7, "gold") # threshold 5000.0
d.addTransaction(7, 3000.0, 10) # -> False (3000.0)
d.addTransaction(7, 2000.0, 20) # -> False (5000.0 equals the threshold and does not exceed it)
d.setUserTier(7, "silver") # threshold 1000.0 from now on
d.addTransaction(7, 50.0, 30) # -> True (5050.0 > 1000.0)
d.getSpending(7, 25) # -> 5000.0 (window -74 .. 25 leaves out the transaction at time 30)
d.getSpending(7, 115) # -> 2050.0 (window 16 .. 115 leaves out the transaction at time 10)
d.getUserTier(8) # -> "silver" (never set)
```
### Constraints & Assumptions
- `1 <= userId <= 10^5`
- `0.0 < amount <= 10^6`
- `0 <= timestamp <= 10^9`
- `windowSize > 0`
- Timestamps for a given user are non-decreasing across `addTransaction` calls. `getSpending` may be called with any timestamp, including one earlier than the user's latest transaction.
- `tier` is one of `'silver'`, `'gold'`, `'platinum'`.
- At most `10^4` calls in total across all methods.
- "Exceeds" means strictly greater than the threshold.
- Every transaction is recorded and counts toward later totals, whether or not it was flagged.
- The check uses the user's tier at the moment of the transaction. A tier change does not revisit earlier results.
### Clarifying Questions to Ask
- When a user changes tier, should transactions that are still inside the window be re-checked against the new threshold, or does the new threshold apply only from the next transaction?
- Do amounts always have two decimal places, or can they carry more precision?
- How long must transaction history be kept, and how many transactions can one user have inside a window?
- Can transactions for the same user arrive concurrently or slightly out of order?
### What a Strong Answer Covers
- The per-user structure for transactions, how the window total is computed or maintained, and the cost of each call.
- The exact window boundary and the strict comparison against the threshold.
- How tier assignment, the `silver` default and reassignment feed into the check.
- How `getSpending` handles query times earlier or later than the user's latest transaction.
- How amounts are summed so that the threshold comparison is exact.
### Follow-up Questions
- Memory grows with every transaction a user makes. How would you bound it, and what would that cost `getSpending`?
- How would you support a different window length per tier, or a second rule such as a limit on the number of transactions?
- Transactions for one user can arrive a few seconds out of order. What changes in the data structure and in the flags already returned?
- How would you spread this across machines for millions of users?
Overview: Design a fraud detector that flags a transaction when a user's spending inside a rolling time window exceeds the threshold for their silver, gold or platinum tier. It tests per-user windowed sums, exact window boundaries, tier reassignment and answering spending queries at arbitrary timestamps.