Here is the full interview question "Coding - Expense Rules Engine" asked at Netflix:
Netflix Interview Question: Coding - Expense Rules Engine
You are given a list of expenses and a set of rules to apply to these expenses. Each rule consists of a condition and an action. The condition can be based on the expense amount, category, or a combination of both. The action can be to add, subtract, or multiply the expense amount by a certain factor. Your task is to implement a system that applies these rules to the expenses and returns the modified expenses.
Examples:
Input:
expenses = [100, 200, 300] rules = [ {"condition": {"amount": 100}, "action": {"type": "add", "value": 50}}, {"condition": {"category": "food"}, "action": {"type": "multiply", "value": 2}}, {"condition": {"amount": 200, "category": "travel"}, "action": {"type": "subtract", "value": 100}} ]
Output:
[150, 300, 200] # 100 + 50, 200 * 2, 300 - 100
Constraints:
Hints:
Solution:
`python def apply_rules(expenses, rules): modified_expenses = expenses[:] rule_map = {}
# Create a map of rules based on their conditions
for rule in rules:
condition = (rule["condition"]["amount"], rule["condition"].get("category"))
if condition not in rule_map:
rule_map[condition] = []
rule_map[condition].append(rule)
# Apply rules to expenses
for i, expense in enumerate(modified_expenses):
for rule in rule_map.get((expense, None), []):
modified_expenses[i] = apply_action(modified_expenses[i], rule["action"])
for rule in rule_map.get((None, None), []):
modified_expenses[i] = apply_action(modified_expenses[i], rule["action"])
return modified_expenses
def apply_action(expense, action): if action["type"] == "add": return expense + action["value"] elif action["type"] == "subtract": return expense - action["value"] elif action["type"] == "multiply": return expense * action["value"]
expenses = [100, 200, 300] rules = [ {"condition": {"amount": 100}, "action": {"type": "add", "value": 50}}, {"condition": {"category": "food"}, "action": {"type": "multiply", "value": 2}}, {"condition": {"amount": 200, "category": "travel"}, "action": {"type": "subtract", "value": 100}} ]
print(apply_rules(expenses, rules)) # Output: [150, 300, 200] `
This solution iterates through the expenses and applies the rules in a single pass. It uses a dictionary to efficiently store and retrieve the rules based on their conditions. The apply_action function handles the different types of actions (add, subtract, multiply). The example usage demonstrates how to apply the rules to the given expenses.