Program to count minimum number of animals which have no predator in Python

Suppose we have a list of numbers called nums where nums[i] shows the predator of the ith animal and if there is no predator, it will hold ?1. We have to find the smallest number of groups of animals such that no animal is in the same group with its direct or indirect predator.

So, if the input is like nums = [1, 2, ?1, 4, 5, ?1], then the output will be 3, as we can have the groups like: [0, 3], [1, 4], [2, 5].

Approach

To solve this, we will follow these steps ?

  • If the array is empty, return 0

  • Create an adjacency list to represent the predator-prey relationships

  • Find all root animals (those with no predator, value = ?1)

  • For each root, perform a depth-first traversal to find the longest chain

  • Return the maximum chain length found

Example

from collections import defaultdict

class Solution:
    def solve(self, A):
        if not A:
            return 0
        
        adj = defaultdict(list)
        vis = set()
        roots = []
        
        for i, a in enumerate(A):
            if a == -1:
                roots.append(i)
            adj[i].append(a)
            adj[a].append(i)
        
        best = -float("inf")
        
        for root in roots:
            stk = [(root, 1)]
            while stk:
                node, d = stk.pop()
                if node in vis or node == -1:
                    continue
                best = max(best, d)
                vis.add(node)
                for u in adj[node]:
                    stk.append((u, d + 1))
        
        return best

# Test the solution
ob = Solution()
nums = [1, 2, -1, 4, 5, -1]
print(ob.solve(nums))
3

How It Works

The algorithm builds a graph where each animal is connected to its predator and prey. Starting from animals with no predators (roots), it performs a depth-first search to find the longest food chain. The maximum chain length represents the minimum number of groups needed.

In the example [1, 2, ?1, 4, 5, ?1]:

  • Animals 2 and 5 have no predators (roots)

  • Chain starting from animal 2: 2 ? 1 ? 0 ? 4 (length 3)

  • Chain starting from animal 5: just 5 (length 1)

  • Maximum chain length is 3

Conclusion

This solution uses graph traversal to find the longest predator-prey chain, which determines the minimum number of groups needed. The time complexity is O(n) where n is the number of animals.

Updated on: 2026-03-25T11:37:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements