Skip to content

Commit d4cd024

Browse files
committed
Sync LeetCode submission Runtime - 4 ms (11.67%), Memory - 18 MB (29.10%)
1 parent c134a3e commit d4cd024

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

0797-rabbits-in-forest/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>There is a forest with an unknown number of rabbits. We asked n rabbits <strong>&quot;How many rabbits have the same color as you?&quot;</strong> and collected the answers in an integer array <code>answers</code> where <code>answers[i]</code> is the answer of the <code>i<sup>th</sup></code> rabbit.</p>
2+
3+
<p>Given the array <code>answers</code>, return <em>the minimum number of rabbits that could be in the forest</em>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> answers = [1,1,2]
10+
<strong>Output:</strong> 5
11+
<strong>Explanation:</strong>
12+
The two rabbits that answered &quot;1&quot; could both be the same color, say red.
13+
The rabbit that answered &quot;2&quot; can&#39;t be red or the answers would be inconsistent.
14+
Say the rabbit that answered &quot;2&quot; was blue.
15+
Then there should be 2 other blue rabbits in the forest that didn&#39;t answer into the array.
16+
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn&#39;t.
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> answers = [10,10,10]
23+
<strong>Output:</strong> 11
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= answers.length &lt;= 1000</code></li>
31+
<li><code>0 &lt;= answers[i] &lt; 1000</code></li>
32+
</ul>

0797-rabbits-in-forest/solution.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Approach: Count
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
from collections import Counter
7+
8+
class Solution:
9+
def numRabbits(self, answers: List[int]) -> int:
10+
count = Counter(answers)
11+
return sum(-v % (k + 1) + v for k, v in count.items())
12+
13+

0 commit comments

Comments
 (0)