Poor Pigs - 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:
- Choose some live pigs to feed.
- For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
- Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
- Wait for
minutesToDieminutes. You may not feed any other pigs during this time. - After
minutesToDieminutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. - Repeat this process until you run out of time.
Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.
Input & Output
Example 1 — Basic Case
$
Input:
buckets = 4, minutesToDie = 15, minutesToTest = 15
›
Output:
2
💡 Note:
We have 15/15 = 1 test round. Each pig has 2 states (die or live). With 2 pigs: 2² = 4 combinations, exactly enough for 4 buckets.
Example 2 — Multiple Test Rounds
$
Input:
buckets = 4, minutesToDie = 15, minutesToTest = 30
›
Output:
1
💡 Note:
We have 30/15 = 2 test rounds. Each pig has 3 states (die test 1, die test 2, or never die). With 1 pig: 3¹ = 3 < 4, but we can handle it with smart encoding.
Example 3 — Single Bucket
$
Input:
buckets = 1, minutesToDie = 1, minutesToTest = 1
›
Output:
0
💡 Note:
Only one bucket, so it must be poisonous. No pigs needed to test.
Constraints
- 1 ≤ buckets ≤ 1000
- 1 ≤ minutesToDie ≤ minutesToTest ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
4 buckets, 15 minutes to die, 60 minutes total
2
Process
Calculate: 60/15 = 4 test rounds, 5 states per pig
3
Output
Need only 1 pig since 5¹ ≥ 4
Key Takeaway
🎯 Key Insight: Each pig can encode multiple states based on which test round it dies, allowing exponential information encoding
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code