LeetCode Solutions
781. Rabbits in Forest
Time: $O(n)$ Space: $O(1000) = O(1)$
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;
}
};
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;
}
}
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