progress

~/problems / Counting / Catalan numbers

Non-crossing handshakes around a table

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

easy basics ~10 min

people people sit around a round table. At once, everyone shakes hands with exactly one other person, and no two handshakes may cross. Seats are numbered, so rotations count as different.

Implement handshakes(people: int) -> int: the number of ways (1 for nobody).

handshakes(4)  # 2    (0-1, 2-3) or (0-3, 1-2); (0-2, 1-3) would cross
handshakes(6)  # 5
handshakes(3)  # 0    someone would be left out

0 <= people <= 1000; return the exact count. The tests go up to 1000 people, so plain recursion without memoisation won't finish.

Show hint

person 0 shakes with some j, splitting the rest into two independent smaller tables, so ways(n) = sum over j of ways(j - 1) * ways(n - j - 1) (only odd j leave both sides even): the Catalan recurrence.

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc