Egg drop puzzle

Find the fewest drops needed, in the worst case, to find the highest floor an egg can be dropped from without breaking.

Time O(eggs × floors²)Space O(eggs × floors)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Dropping an egg from floor x has two outcomes. It breaks: one egg fewer, and only the x-1 floors below are left to search. It survives: the same eggs remain, and only the floors above x are left. dp[k, f] tries every possible x and keeps the one with the smallest worst case.

Code

public static int EggDrop(int eggs, int floors) {
    var dp = new int[eggs + 1, floors + 1];
    for (int f = 1; f <= floors; f++) dp[1, f] = f;
    for (int k = 2; k <= eggs; k++)
        for (int f = 1; f <= floors; f++) {
            dp[k, f] = int.MaxValue;
            for (int x = 1; x <= f; x++) {
                int worst = 1 + Math.Max(dp[k - 1, x - 1], dp[k, f - x]);
                dp[k, f] = Math.Min(dp[k, f], worst);
            }
        }
    return dp[eggs, floors];
}
static int eggDrop(int eggs, int floors) {
    int[][] dp = new int[eggs + 1][floors + 1];
    for (int f = 1; f <= floors; f++) dp[1][f] = f;
    for (int k = 2; k <= eggs; k++)
        for (int f = 1; f <= floors; f++) {
            dp[k][f] = Integer.MAX_VALUE;
            for (int x = 1; x <= f; x++) {
                int worst = 1 + Math.max(dp[k - 1][x - 1], dp[k][f - x]);
                dp[k][f] = Math.min(dp[k][f], worst);
            }
        }
    return dp[eggs][floors];
}
int eggDrop(int eggs, int floors) {
    vector<vector<int>> dp(eggs + 1, vector<int>(floors + 1, 0));
    for (int f = 1; f <= floors; f++) dp[1][f] = f;
    for (int k = 2; k <= eggs; k++)
        for (int f = 1; f <= floors; f++) {
            dp[k][f] = INT_MAX;
            for (int x = 1; x <= f; x++) {
                int worst = 1 + max(dp[k - 1][x - 1], dp[k][f - x]);
                dp[k][f] = min(dp[k][f], worst);
            }
        }
    return dp[eggs][floors];
}
def egg_drop(eggs: int, floors: int) -> int:
    dp = [[0] * (floors + 1) for _ in range(eggs + 1)]
    for f in range(1, floors + 1): dp[1][f] = f
    for k in range(2, eggs + 1):
        for f in range(1, floors + 1):
            dp[k][f] = float('inf')
            for x in range(1, f + 1):
                worst = 1 + max(dp[k - 1][x - 1], dp[k][f - x])
                dp[k][f] = min(dp[k][f], worst)
    return dp[eggs][floors]

Tips

In the .NET library

This brute-force version tries every floor x, costing O(floors) per cell and O(eggs × floors²) overall. A binary search over x, or reframing the state as "trials and eggs" instead of "eggs and floors", brings it down to O(eggs × floors log floors) or better.