Handshakes That Don't Cross - Problem
Non-Crossing Handshakes Problem
Imagine
The challenge: How many different ways can these handshakes occur such that none of the handshake "lines" cross each other?
š¤ Key Constraints:
ā¢
⢠Every person shakes hands with exactly one other person
⢠Handshakes cannot cross when viewed from above the circle
⢠Return the count modulo
Example: With 4 people (A, B, C, D) in a circle, valid arrangements include A-B & C-D, but A-C & B-D would cross!
Imagine
numPeople individuals standing in a perfect circle at a social gathering. Each person must shake hands with exactly one other person, creating numPeople / 2 handshake pairs total.The challenge: How many different ways can these handshakes occur such that none of the handshake "lines" cross each other?
š¤ Key Constraints:
ā¢
numPeople is always even⢠Every person shakes hands with exactly one other person
⢠Handshakes cannot cross when viewed from above the circle
⢠Return the count modulo
109 + 7Example: With 4 people (A, B, C, D) in a circle, valid arrangements include A-B & C-D, but A-C & B-D would cross!
Input & Output
example_1.py ā Basic Case
$
Input:
numPeople = 2
āŗ
Output:
1
š” Note:
With 2 people in a circle, there's only one way to pair them without crossing: person 0 shakes hands with person 1.
example_2.py ā Four People
$
Input:
numPeople = 4
āŗ
Output:
2
š” Note:
With 4 people (0,1,2,3) in a circle: Way 1: (0,1) and (2,3) - adjacent pairs. Way 2: (0,3) and (1,2) - opposite pairs. The pairing (0,2) and (1,3) would cross, so it's invalid.
example_3.py ā Six People
$
Input:
numPeople = 6
āŗ
Output:
5
š” Note:
With 6 people, we get the 3rd Catalan number: C(3) = 5. This follows the pattern: C(0)=1, C(1)=1, C(2)=2, C(3)=5, representing the number of non-crossing handshake arrangements.
Constraints
- 2 ⤠numPeople ⤠1000
- numPeople is always even
- Return result modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Recognize the pattern
This is actually the famous Catalan number sequence in disguise
2
Dynamic programming
Build up solutions from smaller subproblems using C(n) recurrence
3
Optimal calculation
Use the mathematical formula or DP table to compute the nth Catalan number
Key Takeaway
šÆ Key Insight: Non-crossing handshakes in a circle follow the Catalan number sequence - a beautiful connection between geometry and combinatorics!
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code