Poor Pigs — LeetCode 458 Python Solution

HardMathDynamic ProgrammingCombinatorics
Problem
#458
Reading time
2 min

The 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.

Example

Input
buckets = 4, minutesToDie = 15, minutesToTest = 15
Output
2
Explanation
We can determine the poisonous bucket as follows:

Python solution

Python
class Solution:
    def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:
        base = minutesToTest // minutesToDie + 1
        res, p = 0, 1
        while p < buckets:
            p *= base
            res += 1
        return res

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 458. Poor Pigs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 458. Poor Pigs?
LeetCode 458. Poor Pigs is rated Hard on LeetCode.
What topics does LeetCode 458. Poor Pigs cover?
LeetCode 458. Poor Pigs is tagged Math, Dynamic Programming and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview