![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
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.