class Solution { public int numRabbits(int[] answers) { //make a HM to store <answers of rabits , actual rabits> HashMap<Integer,Integer> map = new HashMap<>(); int ans = 0; for(int val : answers){ //if that answer already exists, might mean that rabbit belongs to same colour if(map.containsKey(val)){ //if already that color of rabbits is 0 and still the answer is same means there might be same no. of rabits of different color , so we remove the old color store the answer and add the new color group if(map.get(val) == 0){ ans += val+1; map.put(val , val); } //if answer already exists and there is frequency left,means that rabbit also belong to that same colour and he will take one spot and decrement frequency else{ map.put(val , map.get(val)-1); } } //if answer doesn't already exists means its a new color of rabit else{ map.put(val , val); } } //now add all (keys + 1) values in the answer as while mapping the colour to frequency we already take into account the spot of the rabbit which is giving the answer for(int val : map.keySet()) ans += val+1; return ans; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter