Leetcode 2550: Count Collisions of Monkeys on a Polygon

grid47
grid47
Exploring patterns and algorithms
Feb 26, 2024 6 min read

You are given a regular convex polygon with n vertices. Each vertex has one monkey. Every monkey can move either clockwise or anticlockwise to a neighboring vertex. A collision occurs if two monkeys land on the same vertex or cross paths on an edge. Your task is to return the number of ways the monkeys can move such that at least one collision happens, modulo 10^9 + 7.
Problem
Approach
Steps
Complexity
Input: You are given a single integer `n`, which represents the number of vertices in the polygon.
Example: n = 4
Constraints:
• 3 <= n <= 10^9
Output: Return the number of ways the monkeys can move such that at least one collision happens, modulo 10^9 + 7.
Example: 6
Constraints:
Goal: To calculate the number of collision-producing moves for the monkeys.
Steps:
• 1. Start by calculating the total number of possible movements for the monkeys, which is 2^n.
• 2. Subtract the number of valid movements where no collision occurs (this can be derived from symmetry).
• 3. The result is the number of ways that at least one collision will happen.
Goal: The number of vertices `n` can be as large as 10^9, so the solution needs to be efficient in calculating the result for large inputs.
Steps:
• 3 <= n <= 10^9
Assumptions:
• The monkeys always move simultaneously and only to neighboring vertices.
• The number of possible ways to move can be extremely large, so the result must be computed modulo 10^9 + 7.
Input: n = 4
Explanation: For `n = 4`, there are 16 possible ways the monkeys can move. Among them, 6 ways result in a collision, where at least two monkeys either meet on the same vertex or cross paths.

Input: n = 5
Explanation: For `n = 5`, the total possible movements are 32. Out of them, 10 lead to a collision.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus