458. Poor Pigs

Difficulty:
Related Topics:
Similar Questions:

    Problem

    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:

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

      Example 1:

    Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
    Output: 2
    Explanation: We can determine the poisonous bucket as follows:
    At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
    At time 15, there are 4 possible outcomes:
    - If only the first pig dies, then bucket 1 must be poisonous.
    - If only the second pig dies, then bucket 3 must be poisonous.
    - If both pigs die, then bucket 2 must be poisonous.
    - If neither pig dies, then bucket 4 must be poisonous.
    

    Example 2:

    Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
    Output: 2
    Explanation: We can determine the poisonous bucket as follows:
    At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
    At time 15, there are 2 possible outcomes:
    - If either pig dies, then the poisonous bucket is the one it was fed.
    - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
    At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
    

      Constraints:

    Solution

    /**
     * @param {number} buckets
     * @param {number} minutesToDie
     * @param {number} minutesToTest
     * @return {number}
     */
    var poorPigs = function(buckets, minutesToDie, minutesToTest) {
        return Math.ceil(Math.log2(buckets) / Math.log2(Math.floor(minutesToTest/minutesToDie) + 1));
    };
    

    Explain:

    We have M = minutesToTest/minutesToDie test runs.

    Every pig have M + 1 possible situations, which is die in one of M test runs, or survive at last.

    If we got k pigs, we could have (M + 1) ^ k possibilities.

    If we have to detect one poison bucket in N buckets, we need equal more than N possibilities, which is (M + 1) ^ k >= N.

    Which is k >= log(N) / log(M + 1).

    Complexity: