![]() |
VOOZH | about |
Given N number of bottles in which one bottle is poisoned. So the task is to find out the minimum number of rats required to identify the poisoned bottle. A rat can drink any number of bottles at a time and if any of the taken bottles is poisonous, then the rat dies and cannot drink anymore.
Examples:
Input: N = 4
Output: 2
Explanation: The minimum number of rats needed to find the poisoned bottle among 4 bottles is 2, using binary representation.Input: N = 100
Output: 7
Explanation: Since 2⁷ = 128 can cover up to 100 bottles, a minimum of 7 rats is required for identification.Input: N = 1000
Output: 10
Explanation: The minimum number of rats required is 10, as 210 = 1024 can uniquely identify one poisoned bottle among 1000.
Let's start from the base case.
- For 2 bottles: Taking one rat (R1). If the rat R1 drinks the bottle 1 and dies, then bottle 1 is poisonous.
Else the bottle 2 is poisonous. Hence 1 rat is enough to identify.
- For 3 bottles: Taking two rats (R1) and (R2). If the rat R1 drinks the bottle 1 and bottle 3 and dies, then bottle 1 or bottle 3 is poisonous. So the rat R2 drinks the bottle 1 then. If it dies, then the bottle 1 is poisonous, Else the bottle 3 is poisonous.
Now if the rat R1 does not die after drinking from bottle 1 and bottle 3, then bottle 2 is poisonous.
Hence 2 rats are enough to identify.
- For 4 bottles: Taking two rats (R1) and (R2). If the rat R1 drinks the bottle 1 and bottle 3 and dies, then bottle 1 or bottle 3 is poisonous.
So the rat R2 drinks the bottle 1 then. If it dies, then the bottle 1 is poisonous, Else the bottle 3 is poisonous.
Now if the rat R1 does not die after drinking from bottle 1 and bottle 3, then bottle 2 or bottle 4 is poisonous.
So the rat R1 drinks the bottle 2 then. If it dies, then the bottle 2 is poisonous, Else the bottle 4 is poisonous.
Hence 2 rats are enough to identify.
- For N bottles: Minimum number of rats required are = ceil(log2 N).
Minimum 11 rat(s) are required
Time Complexity: O(1)
Auxiliary Space: O(1)