less than 1 minute read

Problem Statement

leetcode problem link

Brute Force [Accepted]

class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        res = 0
        data = {}
        N = len(answers)
        for i in range(N):
            ans = answers[i]
            if ans == -1:
                continue
            count = 1
            for j in range(i + 1, N):
                if answers[j] == answers[i] and count < ans + 1:
                    answers[j] = -1
                    count += 1
            res += max(count, ans + 1)
        return res

Editorial Solution

Approach #1: Count [Accepted]

class Solution(object):
    def numRabbits(self, answers):
        count = collections.Counter(answers)
        return sum(-v % (k+1) + v for k, v in count.iteritems())