Skip to content

Commit 5cceb5c

Browse files
committedMar 14, 2025
Add solution #781
1 parent d3adbcc commit 5cceb5c

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,7 @@
591591
778|[Swim in Rising Water](./0778-swim-in-rising-water.js)|Hard|
592592
779|[K-th Symbol in Grammar](./0779-k-th-symbol-in-grammar.js)|Medium|
593593
780|[Reaching Points](./0780-reaching-points.js)|Hard|
594+
781|[Rabbits in Forest](./0781-rabbits-in-forest.js)|Medium|
594595
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
595596
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
596597
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|

‎solutions/0781-rabbits-in-forest.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 781. Rabbits in Forest
3+
* https://leetcode.com/problems/rabbits-in-forest/
4+
* Difficulty: Medium
5+
*
6+
* There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have
7+
* the same color as you?" and collected the answers in an integer array answers where answers[i]
8+
* is the answer of the ith rabbit.
9+
*
10+
* Given the array answers, return the minimum number of rabbits that could be in the forest.
11+
*/
12+
13+
/**
14+
* @param {number[]} answers
15+
* @return {number}
16+
*/
17+
var numRabbits = function(answers) {
18+
const colorGroups = {};
19+
let totalRabbits = 0;
20+
21+
for (const answer of answers) {
22+
if (answer === 0) {
23+
totalRabbits++;
24+
continue;
25+
}
26+
27+
if (!colorGroups[answer] || colorGroups[answer] === 0) {
28+
totalRabbits += answer + 1;
29+
colorGroups[answer] = answer;
30+
} else {
31+
colorGroups[answer]--;
32+
}
33+
}
34+
35+
return totalRabbits;
36+
};

0 commit comments

Comments
 (0)
Please sign in to comment.