Handshakes That Don't Cross - Problem
Non-Crossing Handshakes Problem

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 + 7

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!

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
Catalan Numbers: The Hidden Patternn=2: C(1)=1n=3: C(2)=2Catalan Sequence: 1, 1, 2, 5, 14, 42, 132, ...Applications: Parentheses, BSTs, Polygon triangulations, Non-crossing handshakesFormula: C(n) = (2n)! / ((n+1)! Ɨ n!) = Ī£ C(i) Ɨ C(n-1-i)Time: O(n²) | Space: O(n) | The key insight transforms a complex geometry problem into elegant math!šŸ’”
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!
Asked in
Google 45 Amazon 38 Meta 29 Microsoft 22
38.5K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen