Python 0458.py
class Solution:
def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:
# one bucket => it must be poisonous, no tests needed
if buckets == 1:
return 0
# a pig can be tested this often (assuming it survives every time)
maxTests = minutesToTest // minutesToDie
# if buckets <= maxTests then a single pig is enough:
# - give it one bucket a time
# - if the poor pig dies, we know the poisonous bucket
# - if it survives at the end, the untested bucket is poisonous
# - therefore we implicitly tested one more
maxTests += 1
# assume we have 3 buckets in example 2 (instead of 4), then one pig is sufficient:
# - feed bucket 1 at minute 0
# - if pig is dead at minute 15, bucket 1 was poisonous
# - if not, feed it bucket 2 at minute 15
# - if pig is dead at minute 30, bucket 2 was poisonous
# - if not, the untested bucket 3 is poisonous
# therefore 30 // 15 + 1 = 3 buckets were tested with one pig
# if there are multiple pigs p, then assign each bucket a number in base p
# in example 1 there are four buckets 1,2,3,4
# let's convert it from one-based to zero-based numbering: 0,1,2,3
# if we have two pigs then these (binary) numbers would be 00, 01, 10, 11
# the first pig is matched to the first digit, the second to the second digit, and so on
# in round 0 we feed:
# - first pig: bucket 00 and 10 (0 and 2 in decimal => or 1 and 3 in one-based numbering)
# - second pig: bucket 00 and 01 (0 and 1 in decimal => or 1 and 2 in one-based numbering)
# - if both dead, then bucket 00 was the cause
# - if only first pig dead: bucket 10
# - if only second pig dead: bucket 01
# - if both alive, then bucket 11 is bad
capacity = 1
pigs = 0
while capacity < buckets:
# add one more pig
capacity *= maxTests
pigs += 1
return pigs
Difficulty
and has an acceptance rate of about 60% (200k+ submissions).
Typical patterns to solve this problem:
- Combinatorics
- Dynamic Programming
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The routine determines the smallest number of test subjects (pigs) required to identify a single poisonous bucket among a given set. It leverages the fact that each pig can be observed for a fixed number of test rounds before the overall testing deadline expires. By treating the outcome of each pig across the rounds as a digit in a mixed-radix representation, the algorithm computes how many distinct bucket identifiers can be encoded and therefore how many pigs are necessary.
Key Steps
The method begins with a fast-path check for the trivial case where only one bucket exists. In that situation the poisonous bucket is known without any testing, so the function returns zero immediately.
if buckets == 1:
return 0
Next, the algorithm calculates how many separate test intervals are possible within the total testing time. The integer division minutesToTest // minutesToDie yields the number of full intervals a pig can survive, and adding one accounts for the final interval in which a surviving pig still provides information.
maxTests = minutesToTest // minutesToDie
maxTests += 1
The core of the solution is an exponential growth loop that determines how many pigs are needed to cover all bucket possibilities. A variable capacity tracks the total number of distinct bucket identifiers that can be distinguished with the current number of pigs. Starting from one, the loop repeatedly multiplies capacity by maxTests-the number of states each additional pig contributes-while incrementing the pig counter. The loop terminates as soon as capacity meets or exceeds the required number of buckets.
capacity = 1
pigs = 0
while capacity < buckets:
capacity *= maxTests
pigs += 1
Finally, the function returns the accumulated pig count, which represents the minimal number of subjects required to guarantee identification of the poisonous bucket within the allotted time.
return pigs
Edge Cases Handled
When the input specifies a single bucket, the early return bypasses all further calculations, correctly handling the degenerate scenario without unnecessary work.
If the computed maxTests value is large enough that a single pig can differentiate all buckets, the while-loop condition capacity < buckets fails after the first iteration (or even before entering the loop), resulting in a pig count of one. This implicitly covers cases where the number of buckets does not exceed the number of test rounds plus one.
The integer division used to obtain maxTests automatically truncates any fractional remainder, ensuring that only complete test intervals are counted. Adding one afterwards guarantees that the final interval-where a pig may survive the entire testing period-is always considered, even when minutesToTest is an exact multiple of minutesToDie.
The loop’s multiplication approach gracefully handles very large bucket counts because each iteration expands the representable space exponentially, quickly reaching the required capacity without iterating over each bucket individually.
Performance Optimizations
The algorithm avoids any linear scan over the bucket set. By treating the problem as a calculation of the smallest exponent p such that maxTests^p >= buckets, it reduces the work to a logarithmic number of iterations relative to the bucket count. Each loop iteration performs only a constant-time multiplication and increment, leading to a very small overall runtime even for massive inputs.
The early return for buckets == 1 eliminates unnecessary arithmetic for the simplest case.
The use of integer arithmetic throughout (division, multiplication, addition) ensures that the computation remains fast and avoids the overhead of floating-point operations or data structures.
Overall, the method achieves the desired result with minimal computational effort, scaling efficiently as the problem parameters grow.
ELI5 - Simplified Explanation
Imagine a group of buckets filled with water, and one of those buckets has something yucky inside that makes anyone who drinks it get a tummy ache. To figure out which bucket is the bad one, there are special helper pigs. Because the pigs can only drink once in a while, they have to be very smart about how they sip.
First, calculate how many times a single pig can safely test different buckets before the time runs out. If there are only a few buckets, one pig can just try them one by one. If it gets sick after trying a bucket, then that bucket was the yucky one. There is even a clever trick where if the pig stays healthy after tasting all the buckets except for one, then the very last bucket must be the yucky one.
When there are many buckets, one pig is not enough. The strategy is to give each bucket a secret label using a special code. Each pig is assigned a specific part of that code. By watching which pigs get a tummy ache and which stay happy, the combination of healthy and sick pigs acts like a puzzle piece that points directly to the yucky bucket.
To find the right number of pigs for the job, start with one helper and see if they can handle all the buckets. If the number of buckets is bigger than what one pig can test, another pig joins in to help. Keep adding pigs until the group has enough testing power to cover every single bucket. Once the capacity of the group is big enough to cover the count of buckets, there are enough pigs to solve the puzzle.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1360: Number of Days Between Two Dates
- problem 1576: Replace All ?'s to Avoid Consecutive Repeating Characters
- problem 1716: Calculate Money in Leetcode Bank
- problem 2409: Count Days Spent Together
- problem 2515: Shortest Distance to Target String in a Circular Array
- problem 2644: Find the Maximum Divisibility Score
- problem 1110: Delete Nodes And Return Forest
- problem 1296: Divide Array in Sets of K Consecutive Numbers
- problem 1443: Minimum Time to Collect All Apples in a Tree
- problem 1669: Merge In Between Linked Lists
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality