Poor Pigs — LeetCode 458 Python Solution
- Problem
- #458
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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 resComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.