You are given a list of transactions where transactions[i] = [user_id, amount] is a single transaction for user user_id with the given amount. The amount can be positive (a credit) or negative (a debit).
You are also given a list of queries where each element is a user ID. For each query, return the final balance of that user, computed by summing all transaction amounts for that user.
If a queried user has no transactions, their balance is 0. Return the results as a list in the same order as the queries.
Function Signature
def final_balances(transactions: list[list[int]], queries: list[int]) -> list[int]:
...
Rules
-
Each transaction is a two-element list
[user_id, amount]
of integers.
-
Return a list with the same length as
queries
, where entry
i
is the balance of user
queries[i]
.
-
A user ID can appear in many transactions and more than once in
queries
. A repeated query returns the same balance each time.
Constraints
-
1 <= len(transactions) <= 10^5
-
1 <= user_id <= 10^6
-
-10^4 <= amount <= 10^4
-
1 <= len(queries) <= 10^5
-
1 <= queries[i] <= 10^6
Examples
Input: transactions = [[1, 100], [2, 200], [1, -50], [3, 300], [2, -100]], queries = [1, 2, 3, 4]
Output: [50, 100, 300, 0]
User 1 has 100 + (-50) = 50, user 2 has 200 + (-100) = 100, and user 3 has 300. User 4 has no transactions, so the balance is 0.
Input: transactions = [[5, 500], [5, -200], [5, -300]], queries = [5, 6]
Output: [0, 0]
User 5 has 500 + (-200) + (-300) = 0. User 6 has no transactions, so the balance is also 0.