Count Collisions of Monkeys on a Polygon - Problem

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.

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 109 + 7.

Input & Output

Example 1 — Triangle (n=3)
$ Input: n = 3
Output: 6
💡 Note: Total ways = 2³ = 8. Non-collision ways = 2 (all clockwise or all counterclockwise). Collision ways = 8 - 2 = 6.
Example 2 — Square (n=4)
$ Input: n = 4
Output: 14
💡 Note: Total ways = 2⁴ = 16. Non-collision ways = 2. Collision ways = 16 - 2 = 14.
Example 3 — Edge Case (n=1000000000)
$ Input: n = 1000000000
Output: 49
💡 Note: Using modular arithmetic: 2¹⁰⁰⁰⁰⁰⁰⁰⁰⁰ mod (10⁹+7) = 51, so answer is (51-2) mod (10⁹+7) = 49.

Constraints

  • 1 ≤ n ≤ 109
  • Answer modulo 109 + 7

Visualization

Tap to expand
Count Collisions of Monkeys on a Polygon INPUT 0 2 1 M0 M2 M1 n = 3 (3 vertices, 3 monkeys) Each monkey moves to a neighboring vertex clockwise or counter-clockwise 2 choices per monkey ALGORITHM STEPS 1 Total Movements Each monkey: 2 choices Total = 2^n = 2^3 = 8 2 No-Collision Cases All move clockwise: 1 way All move counter-CW: 1 way Safe moves = 2 3 Collision Formula Collisions = Total - Safe = 2^n - 2 4 Calculate Result = 2^3 - 2 = 8 - 2 = 6 For large n, use modular exp: (2^n - 2) mod (10^9 + 7) FINAL RESULT All 8 Combinations: SAFE (No Collision) CW, CW, CW CCW, CCW, CCW COLLISION (6 ways) CW, CW, CCW CW, CCW, CW CCW, CW, CW CCW, CCW, CW CCW, CW, CCW CW, CCW, CCW Output 6 OK - 6 collision ways Formula: 2^n - 2 Key Insight: Only 2 configurations avoid collision: ALL monkeys moving clockwise OR ALL moving counter-clockwise. Any mixed movement guarantees at least one collision (edge crossing or vertex meeting). Time Complexity: O(log n) using fast modular exponentiation | Space: O(1) TutorialsPoint - Count Collisions of Monkeys on a Polygon | Optimal Solution
Asked in
Google 25 Meta 20 Amazon 15
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen