Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
There is a forest with an unknown number of rabbits. We asked n rabbits "How many 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 <= 10000 <= answers[i] < 1000Problem summary: There is a forest with an unknown number of rabbits. We asked n rabbits "How many 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Math · Greedy
[1,1,2]
[10,10,10]
group-the-people-given-the-group-size-they-belong-to)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #781: Rabbits in Forest
class Solution {
public int numRabbits(int[] answers) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : answers) {
cnt.merge(x, 1, Integer::sum);
}
int ans = 0;
for (var e : cnt.entrySet()) {
int group = e.getKey() + 1;
ans += (e.getValue() + group - 1) / group * group;
}
return ans;
}
}
// Accepted solution for LeetCode #781: Rabbits in Forest
func numRabbits(answers []int) (ans int) {
cnt := map[int]int{}
for _, x := range answers {
cnt[x]++
}
for x, v := range cnt {
group := x + 1
ans += (v + group - 1) / group * group
}
return
}
# Accepted solution for LeetCode #781: Rabbits in Forest
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
// Accepted solution for LeetCode #781: Rabbits in Forest
struct Solution;
use std::collections::HashMap;
impl Solution {
fn num_rabbits(answers: Vec<i32>) -> i32 {
let mut hm: HashMap<i32, i32> = HashMap::new();
for x in answers {
*hm.entry(x).or_default() += 1;
}
let mut res = 0;
for (k, v) in hm {
res += (v + k) / (k + 1) * (k + 1);
}
res
}
}
#[test]
fn test() {
let answers = vec![1, 1, 2];
let res = 5;
assert_eq!(Solution::num_rabbits(answers), res);
let answers = vec![10, 10, 10];
let res = 11;
assert_eq!(Solution::num_rabbits(answers), res);
let answers = vec![];
let res = 0;
assert_eq!(Solution::num_rabbits(answers), res);
}
// Accepted solution for LeetCode #781: Rabbits in Forest
function numRabbits(answers: number[]): number {
const cnt = new Map<number, number>();
for (const x of answers) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
let ans = 0;
for (const [x, v] of cnt.entries()) {
const group = x + 1;
ans += Math.floor((v + group - 1) / group) * group;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.