Skip to content

781. Rabbits in Forest

  • Time: $O(n)$
  • Space: $O(1000) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int numRabbits(vector<int>& answers) {
    int ans = 0;
    vector<int> count(1000);

    for (const int answer : answers) {
      if (count[answer] % (answer + 1) == 0)
        ans += answer + 1;
      ++count[answer];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int numRabbits(int[] answers) {
    int ans = 0;
    int[] count = new int[1000];

    for (final int answer : answers) {
      if (count[answer] % (answer + 1) == 0)
        ans += answer + 1;
      ++count[answer];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def numRabbits(self, answers: List[int]) -> int:
    ans = 0
    count = Counter()

    for answer in answers:
      if count[answer] % (answer + 1) == 0:
        ans += answer + 1
      count[answer] += 1

    return ans
Back to top