Design a Transaction Categorization Service with Keyword Rules and Overrides
Company: N26
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a Transaction Categorization Service that classifies incoming financial transactions into spending categories such as `Food`, `Travel`, or `Shopping` based on configurable merchant keyword rules.
The service must support adding rules that map a keyword to a category, recording transactions (each with a merchant and amount), allowing users to override the category of a specific transaction, and reporting total spending per category as well as listing transactions for a given category.
When recording a transaction, the service scans the merchant string for any registered keyword (case-insensitive substring match). If multiple keywords match, the keyword with the highest priority (added most recently) wins. If no keyword matches, the transaction is categorized as `Uncategorized`. A rule applies to transactions recorded after it is added; transactions already recorded keep their category.
Implement the following methods:
- `addRule(keyword: str, category: str)` registers a rule that any transaction whose merchant contains `keyword` (case-insensitive) should be categorized as `category`. Rules added later take priority over earlier ones.
- `recordTransaction(merchant: str, amount: int) -> int` records a new transaction, assigns it the next `transactionId` (starting from 1), categorizes it using the current rules (or `Uncategorized` if none match), updates spend totals, and returns the assigned `transactionId`.
- `overrideCategory(transactionId: int, category: str)` overrides the category of an existing transaction and adjusts the spend totals of both the old and the new category. If `transactionId` does not exist, it does nothing.
- `getCategorySpend(category: str) -> int` returns the total amount currently attributed to `category`, or `0` if the category has no transactions.
- `listTransactionsByCategory(category: str) -> List[int]` returns the `transactionId` values currently classified under `category`, sorted in ascending order (an empty list if there are none).
Example 1:
```text
Input:
["TransactionCategorizationService", "addRule", "addRule", "recordTransaction", "recordTransaction", "recordTransaction", "getCategorySpend", "getCategorySpend", "listTransactionsByCategory"]
[[], ["air", "Travel"], ["cafe", "Food"], ["Airport Cafe", 25], ["SKYAIR Tickets", 40], ["corner bakery", 8], ["Food"], ["Travel"], ["Uncategorized"]]
Output: [null, null, null, 1, 2, 3, 25, 40, [3]]
Explanation:
service = TransactionCategorizationService()
service.addRule("air", "Travel")
service.addRule("cafe", "Food")
service.recordTransaction("Airport Cafe", 25) # -> 1, matches "air" and "cafe"; "cafe" is newer, so Food
service.recordTransaction("SKYAIR Tickets", 40) # -> 2, "skyair" contains "air" (case-insensitive), so Travel
service.recordTransaction("corner bakery", 8) # -> 3, no keyword matches, so Uncategorized
service.getCategorySpend("Food") # -> 25
service.getCategorySpend("Travel") # -> 40
service.listTransactionsByCategory("Uncategorized") # -> [3]
```
Example 2:
```text
Input:
["TransactionCategorizationService", "addRule", "recordTransaction", "recordTransaction", "recordTransaction", "overrideCategory", "overrideCategory", "overrideCategory", "getCategorySpend", "getCategorySpend", "listTransactionsByCategory", "listTransactionsByCategory"]
[[], ["shop", "Shopping"], ["online shop", 120], ["shop 24", 60], ["shoppers mart", 30], [3, "Food"], [1, "Food"], [9, "Travel"], ["Shopping"], ["Food"], ["Food"], ["Travel"]]
Output: [null, null, 1, 2, 3, null, null, null, 60, 150, [1, 3], []]
Explanation:
service.addRule("shop", "Shopping")
service.recordTransaction("online shop", 120) # -> 1, Shopping (Shopping total 120)
service.recordTransaction("shop 24", 60) # -> 2, Shopping (Shopping total 180)
service.recordTransaction("shoppers mart", 30) # -> 3, "shoppers" contains "shop", Shopping (total 210)
service.overrideCategory(3, "Food") # Shopping 180, Food 30
service.overrideCategory(1, "Food") # Shopping 60, Food 150
service.overrideCategory(9, "Travel") # no transaction 9, nothing changes
service.getCategorySpend("Shopping") # -> 60
service.getCategorySpend("Food") # -> 150
service.listTransactionsByCategory("Food") # -> [1, 3], ascending even though 3 moved first
service.listTransactionsByCategory("Travel") # -> []
```
Example 3:
```text
Input:
["TransactionCategorizationService", "recordTransaction", "addRule", "recordTransaction", "addRule", "recordTransaction", "getCategorySpend", "getCategorySpend", "listTransactionsByCategory"]
[[], ["city taxi", 15], ["taxi", "Travel"], ["city taxi", 20], ["city", "Transport"], ["city taxi", 10], ["Uncategorized"], ["Travel"], ["Transport"]]
Output: [null, 1, null, 2, null, 3, 15, 20, [3]]
Explanation:
service.recordTransaction("city taxi", 15) # -> 1, no rules yet, so Uncategorized
service.addRule("taxi", "Travel")
service.recordTransaction("city taxi", 20) # -> 2, Travel
service.addRule("city", "Transport")
service.recordTransaction("city taxi", 10) # -> 3, both match; "city" is newer, so Transport
service.getCategorySpend("Uncategorized") # -> 15, transaction 1 keeps its category
service.getCategorySpend("Travel") # -> 20
service.listTransactionsByCategory("Transport") # -> [3]
```
```hint Rule priority
The newest matching rule wins. Think about the order in which you test rules so that you can stop at the first match.
```
```hint Cheap reports
Totals and listings are read often. Decide what to update on each record and each override so that neither query has to walk every transaction.
```
### Constraints & Assumptions
- `1 <= len(merchant), len(category), len(keyword) <= 50`
- `0 <= amount <= 10^9`
- At most `10^4` total method calls.
- Merchant, keyword and category strings consist of English letters, digits and spaces. Keyword matching ignores case; category names are compared exactly as given.
- `transactionId` values are assigned sequentially starting from `1`.
### Clarifying Questions to Ask
- Are amounts integers in minor units such as cents, so totals can be kept exactly?
- Will the service be called from several threads at once?
- How many rules do you expect compared with the number of transactions, and how often are rules added?
### What a Strong Answer Covers
- Rule matching that follows case-insensitive substring search and newest-rule priority, with `Uncategorized` as the fallback.
- The per-transaction and per-category state that keeps totals and listings consistent after every record and override.
- Behavior for an unknown transaction id, an override to the current category, and a category with no transactions.
- The time and space cost of each method, and where the bottleneck moves as the number of rules grows.
- A total type that cannot overflow at the stated limits.
### Follow-up Questions
- With tens of thousands of rules, how would you categorize a transaction faster than testing every keyword?
- How would you re-categorize existing transactions when a rule is added, without undoing a user's manual overrides?
- How would you make the service safe for concurrent use?
- How would you support per-user rules alongside global ones?
Overview: Design a service that assigns spending categories to financial transactions using case-insensitive merchant keyword rules where the newest rule wins, with manual overrides, per-category totals and sorted listings. It tests hash map bookkeeping, rule priority and keeping derived totals consistent through every update.