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:

  1. Choose some live pigs to feed.
  2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
  3. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
  4. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  5. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  6. 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
Poor Pigs Problem: Find Poisonous Bucket with Minimum PigsB1B2B3B4SafeSafePoisonSafeGiven: 4 buckets, 15 min to die, 60 min totalSmart StrategyTests = 60/15 = 4States per pig = 4+1 = 5Die: T1, T2, T3, T4, Never1 pig × 5 states ≥ 4 bucketsPIGFeeds from B3 in Test 3Dies after Test 3 → B3 is poison!Answer: Only 1 pig needed!
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
Asked in
Google 15 Facebook 10 Amazon 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen