Problem Description
Given an even number of people arranged in a circle, each person shakes hands with someone else in such a way that exactly numPeople / 2 handshakes occur. The handshakes must be arranged so that no two handshakes cross. Return the number of valid handshake arrangements modulo 10^9 + 7.
Key Insights
- The problem is equivalent to counting the number of non-crossing perfect matchings in a circle.
- This count is given by the Catalan numbers; specifically, the nth Catalan number when n = numPeople / 2.
- A dynamic programming (DP) approach can be used where dp[i] represents the number of valid arrangements for 2*i people.
- The recurrence relation is: dp[i] = Σ (dp[j] * dp[i - 1 - j]) for all j from 0 to i-1.
- The modulo operation is applied at every step to keep numbers within bounds.
Space and Time Complexity
Time Complexity: O(n^2) where n = numPeople / 2
Space Complexity: O(n) for the DP array
Solution
We use a DP array where dp[0] is set to 1 (base case with 0 pairs). For each number of pairs i from 1 up to numPeople / 2, we compute dp[i] by iterating j from 0 to i-1 and summing up the product dp[j] * dp[i - 1 - j]. Each multiplication and addition is taken modulo 10^9 + 7. This approach builds the solution using the Catalan number recurrence relation iteratively.