Count Collisions of Monkeys on a Polygon - Problem

Imagine a regular convex polygon with n vertices, where each vertex is labeled from 0 to n-1 in clockwise order. At each vertex sits exactly one monkey, creating a perfect circle of our primate friends!

The Challenge: All monkeys simultaneously decide to move to a neighboring vertex (either clockwise or counterclockwise). A collision occurs when:

  • Two or more monkeys end up on the same vertex after moving
  • Two monkeys cross paths while moving along the same edge

Your Mission: Calculate how many different ways the monkeys can move such that at least one collision happens. Since this number can be astronomically large, return the result modulo 109 + 7.

Key Insight: This is actually a clever math problem in disguise! Think about when collisions DON'T happen, then subtract from the total possibilities.

Input & Output

example_1.py โ€” Basic Triangle
$ Input: n = 3
โ€บ Output: 6
๐Ÿ’ก Note: With 3 monkeys on a triangle, total movements = 2ยณ = 8. Only 2 movements avoid collisions: all clockwise or all counterclockwise. Therefore, collision movements = 8 - 2 = 6.
example_2.py โ€” Square Formation
$ Input: n = 4
โ€บ Output: 14
๐Ÿ’ก Note: With 4 monkeys on a square, total movements = 2โด = 16. Only 2 movements avoid collisions (all same direction). Therefore, collision movements = 16 - 2 = 14.
example_3.py โ€” Minimal Case
$ Input: n = 2
โ€บ Output: 2
๐Ÿ’ก Note: With 2 monkeys on a line (degenerate polygon), total movements = 2ยฒ = 4. Collision-free movements = 2 (both clockwise or both counterclockwise). Answer = 4 - 2 = 2.

Constraints

  • 3 โ‰ค n โ‰ค 109
  • Large input range requires efficient O(log n) solution
  • Result must be returned modulo 109 + 7

Visualization

Tap to expand
Monkey Movement Analysis๐Ÿ’๐Ÿ’๐Ÿ’๐Ÿ’๐Ÿ’๐Ÿ’All ClockwiseAll CounterclockwiseMixed Directions = Collision!Mathematical FormulaTotal Ways: 2^nCollision-Free: 2Answer: 2^n - 2n = 6 monkeysOnly 2 collision-free ways
Understanding the Visualization
1
Setup the Stage
n monkeys on n vertices of a regular polygon, each must move to adjacent vertex
2
Count Total Possibilities
Each monkey has 2 choices (clockwise/counterclockwise) = 2^n total combinations
3
Identify Harmony
Only 2 ways avoid collisions: ALL move clockwise OR ALL move counterclockwise
4
Calculate Chaos
Collision scenarios = Total possibilities - Harmony scenarios = 2^n - 2
Key Takeaway
๐ŸŽฏ Key Insight: In a world of 2^n possibilities, only 2 represent perfect harmony - everyone moving together!
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 24 Apple 18
58.0K Views
Medium Frequency
~15 min Avg. Time
1.5K 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