HardNo. 0458
Poor Pigs — LeetCode 458 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Math, Dynamic Programming, Combinatorics
- 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
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
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
| No. | Problem | Difficulty |
|---|---|---|
| 0062 | Unique Paths | Medium |
| 0920 | Number of Music Playlists | Hard |
| 1359 | Count All Valid Pickup and Delivery Options | Hard |
| 1467 | Probability of a Two Boxes Having The Same Number of Distinct Balls | Hard |
| 1569 | Number of Ways to Reorder Array to Get Same BST | Hard |
| 1621 | Number of Sets of K Non-Overlapping Line Segments | Medium |
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.