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
Monkey Collisions on Polygon (n=4)Initial State01234 vertices, 4 monkeysNo CollisionAll move clockwise: OK ✓All move counterclockwise: OK ✓Collision!Mixed movements: 2+ monkeysend up at same vertex ✗Answer: 2^n - 2 = 16 - 2 = 14 collision ways
Understanding the Visualization
1
Setup
n monkeys on polygon vertices, each moves to adjacent vertex
2
Movement
Each monkey chooses clockwise or counterclockwise
3
Count Collisions
Return number of ways with at least one collision
Key Takeaway
🎯 Key Insight: Only 2 out of 2^n movement patterns avoid collisions
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