Count Collisions of Monkeys on a Polygon Problem
Description
LeetCode Problem 2550.
There is a regular convex polygon with n vertices. The vertices are labeled from 0 to n - 1 in a clockwise direction, and each vertex has exactly one monkey. The following figure shows a convex polygon of 6 vertices.

Simultaneously, each monkey moves to a neighboring vertex. A collision happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.
Return the number of ways the monkeys can move so that at least one collision happens. Since the answer may be very large, return it modulo 10^9+ 7.
Example 1:
Input: n = 3
Output: 6
Explanation:
There are 8 total possible movements.
Two ways such that they collide at some point are:
- Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.
- Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.
Example 2:
Input: n = 4
Output: 14
Constraints:
3 <= n <= 10^9
Solution
Approach: Counting with Fast Power
Each monkey picks one of two directions, so there are 2n ways to move in total. Only two of them avoid every collision: all monkeys go clockwise, or all go counterclockwise. The answer is therefore 2n - 2, taken modulo 109 + 7.
Since n can be as large as 109, compute 2n by fast exponentiation (repeated squaring), reducing modulo 109 + 7 at every step.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def monkeyMove(self, n: int) -> int:
mod = 10**9 + 7
return (pow(2, n, mod) - 2) % mod