Handshakes That Don't Cross — LeetCode 1259 Python Solution

HardLeetCode PremiumMathDynamic Programming
Problem
#1259
Reading time
3 min

The problem

You are given an even number of people numPeople that stand around a circle and each person shakes hands with someone else so that there are numPeople / 2 handshakes total. Return the number of ways these handshakes could occur such that none of the handshakes cross.

Example

Input
numPeople = 4
Output
2
Explanation
There are two ways to do it, the first way is [(1,2),(3,4)] and the second one is [(2,3),(4,1)].

Python solution

Python
class Solution:
    def numberOfWays(self, numPeople: int) -> int:
        @cache
        def dfs(i: int) -> int:
            if i < 2:
                return 1
            ans = 0
            for l in range(0, i, 2):
                r = i - l - 2
                ans += dfs(l) * dfs(r)
                ans %= mod
            return ans

        mod = 10**9 + 7
        return dfs(numPeople)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1259. Handshakes That Don't Cross is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1259. Handshakes That Don't Cross?
LeetCode 1259. Handshakes That Don't Cross is rated Hard on LeetCode.
What is the time complexity of LeetCode 1259. Handshakes That Don't Cross?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1259. Handshakes That Don't Cross?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1259. Handshakes That Don't Cross cover?
LeetCode 1259. Handshakes That Don't Cross is tagged Math and Dynamic Programming on LeetCode.
Is LeetCode 1259. Handshakes That Don't Cross a premium problem?
Yes. LeetCode 1259. Handshakes That Don't Cross is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview