progress

~/problems / Weighted graphs / Union-Find

Pooled lunch money

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

Office workers 0 .. n-1 start with money[i] coins. When two people pool, everyone in either pool shares one pot from then on (pooling is transitive and never undone).

Process events in order:

  • ("pool", a, b): merge the pots of a and b (no change if already shared).
  • ("ask", a): how many coins are in a's pot now?

Implement pot_sizes(money: list[int], events: list[tuple]) -> list[int]: the answers to the asks, in order.

money = [5, 1, 7, 2]
events = [("ask", 0), ("pool", 0, 1), ("ask", 1), ("pool", 2, 3), ("pool", 1, 3), ("ask", 2), ("pool", 0, 2), ("ask", 3)]
pot_sizes(money, events)   # [5, 6, 15, 15]

Up to 10^5 people and 2 * 10^5 events; asks and pools are interleaved.

⭐ Bonus: a speed test with 100,000 asks on a big pot earns a star if each ask is near O(1), instead of walking the whole pot.

Show hint

union-find with a total per root; when two roots merge, add the absorbed root's total to the survivor's.

Topic: Union-Find. Path compression + union by rank; connectivity and grouping.

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