Given N eggs and K floors, the task is to find the minimum number of trials needed, in the worst case, to find the floor below which all floors are safe. A floor is safe if dropping an egg from it does not break the egg. Please refer n eggs and k floors for more insight.
Input: N = 2, K = 10
The first trial was on the 4th floor. Two cases arise after this:
- If the egg breaks, we have one egg left, so we need three more trials.
- If the egg does not break, the next try is from the 7th floor. Again, two cases arise.
Input: N = 2, K = 100
Prerequisites: Egg Dropping Puzzle
Approach: Consider this problem in a different way:
Let dp[x][n] is the maximum number of floors that can be checked with given n eggs and x moves.
Then the equation is:
- If the egg breaks, then we can check dp[x – 1][n – 1] floors.
- If the egg doesn’t break, then we can check dp[x – 1][n] + 1 floors.
Since we need to cover k floors, dp[x][n] >= k.
dp[x][n] is similar to the number of combinations and it increases exponentially to k
Below is the implementation of the above approach:
Time Complexity: O(NlogK)
Space Complexity: O(N * K)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live