Skip to content

Instantly share code, notes, and snippets.

@SuryaPratapK
Created April 20, 2025 10:09
Show Gist options
  • Save SuryaPratapK/9777675614da5af9c40de6cbba027b72 to your computer and use it in GitHub Desktop.
Save SuryaPratapK/9777675614da5af9c40de6cbba027b72 to your computer and use it in GitHub Desktop.
class Solution {
public:
int numRabbits(vector<int>& answers) {
int n = answers.size();
unordered_map<int,int> group_freq;
int count = 0;
//Insert all elements and count full_group_elements
for(int ele: answers){
if(ele==0)
count += 1;
else{
group_freq[ele]++;
if(group_freq[ele]==ele+1){
count += ele+1;
group_freq[ele]=0;
}
}
}
//Add leftover
for(auto [group,freq]: group_freq)
if(freq>0)
count += group+1;
return count;
}
};
/*
//JAVA
import java.util.HashMap;
class Solution {
public int numRabbits(int[] answers) {
HashMap<Integer, Integer> groupFreq = new HashMap<>();
int count = 0;
for (int ele : answers) {
if (ele == 0) {
count += 1;
} else {
groupFreq.put(ele, groupFreq.getOrDefault(ele, 0) + 1);
if (groupFreq.get(ele) == ele + 1) {
count += ele + 1;
groupFreq.put(ele, 0);
}
}
}
for (int key : groupFreq.keySet()) {
int freq = groupFreq.get(key);
if (freq > 0) {
count += key + 1;
}
}
return count;
}
}
#Python
from collections import defaultdict
class Solution:
def numRabbits(self, answers: List[int]) -> int:
group_freq = defaultdict(int)
count = 0
for ele in answers:
if ele == 0:
count += 1
else:
group_freq[ele] += 1
if group_freq[ele] == ele + 1:
count += ele + 1
group_freq[ele] = 0
for group, freq in group_freq.items():
if freq > 0:
count += group + 1
return count
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment