Skip to content

2550. Count Collisions of Monkeys on a Polygon 👎

  • Time: $O(\log n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int monkeyMove(int n) {
    const int res = modPow(2, n) - 2;
    return res < 0 ? res + kMod : res;
  }

 private:
  static constexpr int kMod = 1'000'000'007;

  long modPow(long x, long n) {
    if (n == 0)
      return 1;
    if (n % 2 == 1)
      return x * modPow(x % kMod, (n - 1)) % kMod;
    return modPow(x * x % kMod, (n / 2)) % kMod;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int monkeyMove(int n) {
    final int res = (int) modPow(2, n) - 2;
    return res < 0 ? res + kMod : res;
  }

  private static final int kMod = 1_000_000_007;

  private long modPow(long x, long n) {
    if (n == 0)
      return 1;
    if (n % 2 == 1)
      return x * modPow(x, n - 1) % kMod;
    return modPow(x * x % kMod, n / 2);
  }
}
1
2
3
4
5
class Solution:
  def monkeyMove(self, n: int) -> int:
    kMod = 1_000_000_007
    res = pow(2, n, kMod) - 2
    return res + kMod if res < 0 else res