Similar Problems

Similar Problems not available

Rabbits In Forest - Leetcode Solution

Companies:

LeetCode:  Rabbits In Forest Leetcode Solution

Difficulty: Medium

Topics: greedy hash-table math array  

Problem statement: There are n rabbits in the forest, and each rabbit has a unique id between 0 and n-1. There are also m direct connections among rabbits in the forest, where connections[i] = [x, y] represents a connection between rabbits x and y. A rabbit m1 can infect another rabbit m2 if and only if m1 and m2 are directly connected and m1 is older than m2. Every rabbit can infect at most one other rabbit. Given the connections, the number of rabbits that are infected in the end after all possible infections have been made is defined as the rabbit infection number. Return the rabbit infection number.

Solution: The given problem can be solved using Union-Find algorithm. We can create a disjoint set of all the rabbits and their connections. The implementation of the algorithm will be as follows:

  1. Create a list of n disjoint set, where each set contains only one rabbit.
  2. Iterate through all the connections and merge the disjoint set containing x and y, where x and y are the connected rabbits.
  3. After merging each set, we store the minimum rabbit id in that merged set.
  4. We then iterate through all the rabbits and find the root of their set. If the rabbit is not a root, it means it is infected by a rabbit that is older than it. We can update the infection count and return it.

Implementation:

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.min_rabbit = list(range(n))
    
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    
    def union(self, x, y):
        x_root = self.find(x)
        y_root = self.find(y)
        if x_root != y_root:
            self.parent[x_root] = y_root
            self.min_rabbit[y_root] = min(self.min_rabbit[x_root], self.min_rabbit[y_root])


class Solution:
    def findRabbitInfection(self, n: int, connections: List[List[int]]) -> int:
        dsu = DSU(n)
        for x, y in connections:
            dsu.union(x, y)
        
        infection_count = 0
        for i in range(n):
            if dsu.find(i) == i:
                infection_count += 1
            elif dsu.min_rabbit[dsu.find(i)] < i:
                infection_count += 1
        
        return infection_count

Time Complexity: O(n * alpha(n)), where alpha(n) is the inverse Ackermann function. This is almost constant for all practical purposes.

Space Complexity: O(n) for DSU class.

Rabbits In Forest Solution Code

1