Count Collisions of Monkeys on a Polygon — LeetCode 2550 Python Solution

MediumRecursionMath
Problem
#2550
Reading time
2 min

The 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.

Python solution

Python
class Solution:
    def monkeyMove(self, n: int) -> int:
        mod = 10**9 + 7
        return (pow(2, n, mod) - 2) % mod

Complexity

MeasureComplexity
TimeO(\log n), where n is the number of monkeys
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2550. Count Collisions of Monkeys on a Polygon is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2550. Count Collisions of Monkeys on a Polygon?
LeetCode 2550. Count Collisions of Monkeys on a Polygon is rated Medium on LeetCode.
What is the time complexity of LeetCode 2550. Count Collisions of Monkeys on a Polygon?
The Python solution on this page runs in O(\log n), where n is the number of monkeys.
What is the space complexity of LeetCode 2550. Count Collisions of Monkeys on a Polygon?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2550. Count Collisions of Monkeys on a Polygon cover?
LeetCode 2550. Count Collisions of Monkeys on a Polygon is tagged Recursion and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview