You’re building a real-time fintech risk dashboard that monitors millions of brokerage sub-accounts grouped into “portfolios” (e.g., household, advisor book, or strategy bucket). Traders and compliance teams rely on instant portfolio totals to enforce margin rules and detect suspicious activity.
You are given an initial in-memory state with:
account_balance: mapping account_id -> balanceportfolio_accounts: mapping portfolio_id -> list of account_ids (each account belongs to exactly one portfolio at any time)Then you receive a stream of actions (strings). You must process them in order and return the results of every query.
ADD_ACCOUNT user_id portfolio_id account_id balance
portfolio_id.UPDATE_BALANCE account_id new_balance
MOVE_ACCOUNT account_id from_portfolio_id to_portfolio_id
QUERY_PORTFOLIO_TOTAL portfolio_id
Implement:
def process_actions(initial_state: dict, actions: list[str]) -> list[int]:
Return a list of integers containing the results of each QUERY_PORTFOLIO_TOTAL in order.
initial_state may contain them as strings (JSON input). Your solution must handle both.0.MOVE_ACCOUNT always specifies the account’s current portfolio as from_portfolio_id.Example 1
initial_state = {'portfolio_accounts': {1: [10, 11]}, 'account_balance': {10: 50, 11: 70}}actions = ['QUERY_PORTFOLIO_TOTAL 1', 'UPDATE_BALANCE 10 80', 'QUERY_PORTFOLIO_TOTAL 1'][120, 150]Example 2
initial_state = {'portfolio_accounts': {1: [10], 2: [20]}, 'account_balance': {10: 5, 20: 7}}actions = ['MOVE_ACCOUNT 10 1 2', 'QUERY_PORTFOLIO_TOTAL 1', 'QUERY_PORTFOLIO_TOTAL 2'][0, 12]