VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-ways-to-handshakes-that-dont-cross/

⇱ Number of Ways to Handshakes That Don't Cross - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of Ways to Handshakes That Don't Cross

Last Updated : 30 May, 2024

Given an even number of people n, who are standing in a circle. Each person shakes hands with one other person, resulting in a total of n/2 handshakes. The task is to find the number of ways these handshakes can occur such that none of the handshakes cross. Since the answer could be very large, you need to return the result modulo 10^9 + 7.

Example:

Input: n = 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)].

Input: n = 6
Output: 5

Approach:

The idea behind the solution is to use a dynamic programming array dp, where dp[i] represents the number of ways to arrange i people in a circle without any handshakes crossing. The base case is straightforward: dp[0] is 1, as there is exactly one way to arrange zero people (an empty arrangement). For each even number i from 2 to n, considers different possible positions for the first person to shake hands, effectively dividing the problem into smaller subproblems. For each position j, calculates the number of ways to arrange the remaining people on either side of the handshake. The results are combined, taking into account symmetry (clockwise and counterclockwise arrangements). By iterating through all possible configurations and combining the results using modular arithmetic to handle large numbers, builds up the solution incrementally.

Steps-by-step appraoch:

  • Loop through i (number of people, starting from 2, increment by 2).
    • For each i:
    • Loop through j (possible positions for first person, increment by 2).
    • Calculate dp[i] based on j:
      • If j is last person, add dp[j] * dp[i-j-2] % mod.
      • Otherwise, add 2 * (dp[j] % mod) * (dp[i-j-2] % mod) % mod.
    • Return dp[n] (number of ways for n).

Below is the implementation of the above approach:


Output
The number of ways to arrange 4 people in a circle is 2

Time Complexity: O(n^2) due to nested loops.
Auxiliary Space: O(n) due to dp vector.


Comment
Article Tags: