progress

~/problems / Arrays & hashing / Hash maps and counting

Percentage transfers between accounts

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Coinbase

A wallet moves money in chunks that are a percentage of the sender's current balance, in whole cents.

Implement TransactionSystem:

  • __init__(accounts: list[tuple[str, int]]): starting (name, balance) pairs.
  • transfer(sender: str, receiver: str, percent: int) -> int: move floor(balance(sender) * percent / 100) and return it. If an account is unknown, sender == receiver, or percent is outside 0..100, change nothing and return -1.
  • process(transactions: list[tuple[str, str, int]]) -> list[int]: apply transfers in order, returning each result (-1 for invalid ones).
  • balance(name: str) -> int | None: the balance, or None if unknown.
  • richest(k: int) -> list[str]: the k richest names, highest first, ties by name ascending (all if fewer than k).
ts = TransactionSystem([("ana", 1000), ("ben", 500), ("cy", 0)])
ts.transfer("ana", "ben", 25)      # 250   ana 750, ben 750
ts.transfer("ben", "cy", 33)       # 247   floor(750 * 33 / 100); ben 503, cy 247
ts.process([("cy", "ana", 100), ("ana", "zed", 10), ("ana", "ana", 5)])
# [247, -1, -1]                    ana 997, cy 0
ts.richest(2)                      # ["ana", "ben"]
ts.balance("zed")                  # None

Up to 10^5 accounts and transfers. ⭐ Bonus: a speed test earns a star for O(1) transfers (sorting in richest is fine).

Show hint

a dict from name to balance; use balance * percent // 100, not floats.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc