Problem
You are given k
identical eggs and you have access to a building with n
floors labeled from 1
to n
.
You know that there exists a floor f
where 0 <= f <= n
such that any egg dropped at a floor higher than f
will break, and any egg dropped at or below floor f
will not break.
Each move, you may take an unbroken egg and drop it from any floor x
(where 1 <= x <= n
). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f
is.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Using DP
- Problem Breakdown:
- You have
k
eggs andn
floors. - If an egg breaks, the floors above are unsafe (the critical floor is in the floors below).
- If an egg doesn’t break, the critical floor is in the floors above.
- You have
- Goal:
- Minimise the worst-case number of moves required to find the floor
f
.
- Minimise the worst-case number of moves required to find the floor
- Key Observations:
- If you have just one egg, you’ll need to check each floor sequentially from
1
ton
. This takesn
moves in the worst case. - If you have many eggs, you can use a binary-like search pattern to minimise the number of moves—splitting the problem space into halves repeatedly.
- If you have just one egg, you’ll need to check each floor sequentially from
- Approach:
- We’ll define
dp[k][n]
as the minimum number of moves required to findf
withk
eggs andn
floors. - When dropping an egg from floor
x
:- If the egg breaks, the problem reduces to
dp[k-1][x-1]
(fewer eggs and fewer floors belowx
). - If the egg doesn’t break, the problem reduces to
dp[k][n-x]
(same eggs but fewer floors abovex
).
- If the egg breaks, the problem reduces to
- The recurrence relation becomes:
1
dp[k][n] = 1 + min(max(dp[k-1][x-1], dp[k][n-x]) for x in range(1, n+1)).
- We’ll define
- Optimisation:
- Instead of testing every floor
x
linearly, a binary search can be applied onx
due to the “minimum of maximums” structure.
- Instead of testing every floor
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k * n * log(n))
- The brute-force DP approach has
O(k * n^2)
complexity due to nested loops. - Using binary search for the inner loop reduces the complexity to
O(k * n * log(n))
.
- The brute-force DP approach has
- 🧺 Space complexity:
O(k*n)
. The space complexity isO(k * n)
because of the DP table.