Problem 458

Abstract / Summary

Determine the minimum number of pigs needed to find which of several buckets contains poison using a set number of testing turns.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
42 lines | 2122 bytes | submitted December 6, 2023 | GitHub   225% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (200k+ submissions).

Typical patterns to solve this problem:
  • Combinatorics
  • Dynamic Programming
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.81 | σ = 0.98

Complexity Analysis

Time: logarithmic
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
35 links | 23 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   December 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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