#1884
Egg Drop With 2 Eggs and N Floors
MediumMathDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses a dynamic programming approach to minimize the number of drops. We can leverage the fact that we can drop the first egg from a calculated floor and use the results to narrow down the possible floors more efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP table where dp[i][j] represents the minimum number of drops needed with i eggs and j floors.
- 2Step 2: Initialize the base cases for 1 egg and j floors, and for i eggs and 0 floors.
- 3Step 3: Fill the DP table using the recurrence relation: dp[i][j] = min(1 + max(dp[i-1][x-1], dp[i][j-x])) for all x from 1 to j.
solution.py11 lines
1def eggDrop(n):
2 dp = [[0] * (n + 1) for _ in range(3)]
3 for j in range(1, n + 1):
4 dp[1][j] = j
5 for i in range(2, 3):
6 for j in range(1, n + 1):
7 dp[i][j] = float('inf')
8 for x in range(1, j + 1):
9 res = 1 + max(dp[i-1][x-1], dp[i][j-x])
10 dp[i][j] = min(dp[i][j], res)
11 return dp[2][n]ℹ
Complexity note: The time complexity is O(n²) due to the nested loops for filling the DP table, while the space complexity is O(n) for storing the results in the DP table.
- 1Using dynamic programming allows us to break down the problem into smaller subproblems and build up the solution efficiently.
- 2The choice of where to drop the first egg can significantly affect the total number of drops needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.