progress

~/problems / Counting / Catalan numbers

Arm-wrestling along a bench

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

medium ~20 min

players arm-wrestlers sit in a row. A bout is between two bench neighbours; the loser leaves and the row closes up, until one champion is left.

Only the shape of the contest matters: which blocks of original seats each bout merges. The order of independent bouts doesn't: with 4 players, "1-2 and 3-4 wrestle, then the two winners" is one shape.

Implement bench_shapes(players: int) -> int: the number of shapes.

bench_shapes(1)  # 1    nobody wrestles
bench_shapes(3)  # 2    (1 vs 2) then vs 3,  or  1 vs (2 vs 3)
bench_shapes(4)  # 5

1 <= players <= 600; return the exact count. Recursion without memoisation is exponential and won't finish for the larger tests.

⭐ Bonus: a speed test with 600 players earns a star in O(n²), working out each smaller count once.

Show hint

the final bout joins seats 1..i with i+1..players, each side having had its own contest, so shapes(n) = sum over i of shapes(i) * shapes(n - i): the Catalan recurrence, shifted by one.

Topic: Catalan numbers. C(n) = sum C(i) C(n-i-1): trees, parenthesizations.

0:00
Ctrl ' run · Ctrl ↵ submit
esc