Handshakes That Don't Cross - Problem

You are given an even number of people numPeople that stand around a circle. Each person must shake hands with exactly one other person, resulting in numPeople / 2 handshakes total.

Return the number of ways these handshakes could occur such that none of the handshakes cross. Since the answer could be very large, return it modulo 10⁹ + 7.

Two handshakes cross if the line segments connecting the pairs of people intersect when drawn inside the circle.

Input & Output

Example 1 — Basic Case
$ Input: numPeople = 4
Output: 2
💡 Note: Person 0 can shake hands with person 1 (leaving 2,3 as a pair) or with person 3 (leaving 1,2 as a pair). Both arrangements have no crossing handshakes.
Example 2 — Larger Circle
$ Input: numPeople = 6
Output: 5
💡 Note: With 6 people in a circle, there are 5 different ways to arrange 3 handshakes without any crossings. This corresponds to the 3rd Catalan number.
Example 3 — Minimum Case
$ Input: numPeople = 2
Output: 1
💡 Note: Only one way exists: the two people shake hands with each other. No crossings possible.

Constraints

  • 2 ≤ numPeople ≤ 1000
  • numPeople is even

Visualization

Tap to expand
Handshakes That Don't Cross INPUT 0 1 2 3 numPeople = 4 4 people, 2 handshakes Even number standing in circle ALGORITHM STEPS 1 Catalan Numbers C(n) counts valid pairings 2 DP Recurrence dp[i] = sum(dp[j]*dp[i-j-2]) 3 Base Cases dp[0]=1, dp[2]=1 4 Compute dp[4] Return result mod 10^9+7 DP Table i=0 1 i=2 1 i=4 2 i=6 5 dp[4] = dp[0]*dp[2] + dp[2]*dp[0] dp[4] = 1*1 + 1*1 = 2 FINAL RESULT Way 1: (0-1, 2-3) 0 1 2 3 Way 2: (0-3, 1-2) 0 1 2 3 Output: 2 OK - No crossing! Key Insight: This problem follows the Catalan number sequence. Person 0 must shake hands with an odd-numbered person, dividing the circle into two independent groups. We recursively count valid pairings in each group. The n-th Catalan number C(n) = dp[2n] gives the answer. Time: O(n^2), Space: O(n). TutorialsPoint - Handshakes That Don't Cross | Optimal DP Solution
Asked in
Google 15 Microsoft 12 Facebook 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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