LeetCode 0781. Rabbits in Forest Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0781. Rabbits in Forest

Description

There is a forest with an unknown number of rabbits. We asked n rabbits "How many other rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.

Given the array answers, return the minimum number of rabbits that could be in the forest.

 

Example 1:

Input: answers = [1,1,2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

Example 2:

Input: answers = [10,10,10]
Output: 11

 

Constraints:

  • 1 <= answers.length <= 1000
  • 0 <= answers[i] < 1000

Solutions

Solution 1: Greedy + Hash Map

According to the problem description, rabbits that give the same answer may belong to the same color, while rabbits that give different answers cannot belong to the same color.

Therefore, we use a hash map cnt to record the number of occurrences of each answer. For each answer x and its occurrence v, we calculate the minimum number of rabbits based on the principle that each color has x + 1 rabbits, and add it to the answer.

The time complexity is O(n), and the space complexity is O(n). Where n is the length of the array answers.

PythonJavaC++GoTypeScript
class Solution: def numRabbits(self, answers: List[int]) -> int: cnt = Counter(answers) ans = 0 for x, v in cnt.items(): group = x + 1 ans += (v + group - 1) // group * group return ans(code-box)

Solution 2: Greedy + Hash Map

TypeScriptJavaScript
function numRabbits(answers: number[]): number { const cnt: Record<number, number> = {}; let ans = 0; for (const x of answers) { if (cnt[x]) { cnt[x]--; } else { cnt[x] = x; ans += x + 1; } } return ans; }(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !