← Gym/Normalize Transactions
00:00/ 12 min

🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.

You are given an account system's transaction log in chronological order. Each line is one deposit or withdrawal, and the same user appears many times.

Implement calculate_balances(transactions), which sums every transaction per user to produce a final balance.

Input

python
transactions = [("alice", 100), ("bob", -30), ("alice", 50), ("bob", 20)]
  • Each entry is a (user, amount) pair.
  • Amounts are integers. Positive is a deposit, negative a withdrawal.
  • The same user may appear many times.

Output

Return a list of (user, balance) tuples sorted by user name in ascending order.

python
calculate_balances(transactions)
# [("alice", 150), ("bob", -10)]

Where each value comes from:

  • alice: 100 in, then 50 more in, so 150.
  • bob: 30 out, then 20 in, so -10. A negative balance stays negative.

The result is ordered by sorted name, not by order of appearance. alice happens to come first in the input, but even if bob had come first the result would still be [("alice", 150), ("bob", -10)].

The sort order

Use Python's default string comparison — the same result as calling sorted without a key.

That comparison follows character codes, so uppercase sorts before lowercase. Sorting "Banana" and "apple" puts "Banana" first. It reads oddly as dictionary order, but here that behavior is the correct answer.

Things to watch

  1. A user who transacted at least once stays in the result even when the balance reaches zero. Someone who deposited 100 and withdrew 100 appears as ("a", 0).
  2. A user with no transactions never appears in the input, so there is nothing to consider there.
  3. If one user has ten transactions, all ten are summed.
  4. Empty input returns an empty list.

Level 1 · Aggregating balances

Implement calculate_balances(transactions).