In this Leetcode Poor Pigs problem solution There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.

You can feed the pigs according to these steps:

  1. Choose some live pigs to feed.
  2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
  3. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  4. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  5. Repeat this process until you run out of time.

Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.

Leetcode Poor Pigs problem solution


Problem solution in Python.

def poorPigs(self, buckets, minutesToDie, minutesToTest):
    pigs = 0
    while (minutesToTest / minutesToDie + 1) ** pigs < buckets:
        pigs += 1
    return pigs



Problem solution in Java.

public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
    return (int)Math.ceil(Math.log(buckets)/Math.log(minutesToTest/minutesToDie+1));
}


Problem solution in C++.

int numIntervals = minutesToTest/minutesToDie+1;
    
    if(buckets==1)
        return 0;
    
    
    int numStatesPossible=numIntervals;
    int pig=1;
    while(pig<32 && numStatesPossible<buckets){
        numStatesPossible = numStatesPossible*numIntervals;
        pig++;
    }
    return pig;
}