Super Egg Drop — LeetCode 887 Python Solution
- Problem
- #887
- Pattern
- Monotonic Stack
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- k = 1, n = 2
- Output
- 2
- Explanation
- Drop the egg from floor 1. If it breaks, we know that f = 0.
Python solution
class Solution:
def superEggDrop(self, k: int, n: int) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i < 1:
return 0
if j == 1:
return i
l, r = 1, i
while l < r:
mid = (l + r + 1) >> 1
a = dfs(mid - 1, j - 1)
b = dfs(i - mid, j)
if a <= b:
l = mid
else:
r = mid - 1
return max(dfs(l - 1, j - 1), dfs(i - l, j)) + 1
return dfs(n, k)Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 887. Super Egg Drop is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 887. Super Egg Drop?
- LeetCode 887. Super Egg Drop is rated Hard on LeetCode.
- What topics does LeetCode 887. Super Egg Drop cover?
- LeetCode 887. Super Egg Drop is tagged Math, Binary Search and Dynamic Programming on LeetCode.