Egg Dropping Puzzle | DP-11
Last Updated : 25 Mar, 2025
You are given n identical eggs and you have access to a k-floored building from 1 to k.
There exists a floor f where 0 <= f <= k such that any egg dropped from a floor higher than f will break, and any egg dropped from or below floor f will not break. There are a few rules given below:
- An egg that survives a fall can be used again.
- A broken egg must be discarded.
- The effect of a fall is the same for all eggs.
- If the egg doesn't break at a certain floor, it will not break at any floor below.
- If the egg breaks on a certain floor, it will break on any floor above.
Your task is to find the minimum number of moves you need to determine the value of f with certainty.
Example:
Input: n = 2, k = 36
Output: 8
Explanation: In all the situations, 8 maximum moves are required to find the maximum floor. Following is the strategy to do so:
- Drop from floor 8 → If breaks, check 1-7 sequentially.
- Drop from floor 15 → If breaks, check 9-14.
- Drop from floor 21 → If breaks, check 16-20.
- Drop from floor 26 → If breaks, check 22-25.
- Drop from floor 30 → If breaks, check 27-29.
- Drop from floor 33 → If breaks, check 31-32.
- Drop from floor 35 → If breaks, check 34.
- Drop from floor 36 → Final check.
Input: n = 1, k = 36
Output: 36
Explanation: Drop the egg from the first-floor window; if it survives, drop it from the second-floor window. Continue upward until it breaks. In the worst case, this method may require 36 droppings.
Input: n = 2, k = 10
Output: 4
Explanation: In all the situations, 4 maximum moves are required to find the maximum floor. Following is the strategy to do so:
- Drop from floor 4 → If breaks, check 1-3 sequentially.
- Drop from floor 7 → If breaks, check 5-6.
- Drop from floor 9 → If breaks, check 8.
- Drop from floor 10 → Final check.
[Naive Approach] Using Recursion - O(n ^ k) Time and O(1) Space
The idea is to try dropping an egg from every floor (from 1 to K) and recursively calculate the minimum number of droppings needed in the worst case. To do so, run a loop from x equal to 1 to K, where i denotes the current floor. When we drop an egg from floor i, there are two possibilities:
- If the egg breaks: Then we need to check for floors lower than i with 1 less egg, i.e. the value of both egg and floor will be reduced by 1.
- If the egg doesn't break: Then we need to check for floors higher than i with same number of eggs, i.e. the number of floors to check will be k - i, and the count of eggs will remain same.
The maximum of these two move + 1(current move) will be considered, and the minimum of this is our answer.
For each recursive call, follow the below given steps:
- If k == 1 or k == 0 then return k, i.e. is we need to check only 1 or no floors.
- If n == 1 return k, i.e. we need to check all floors starting from the first one.
- Create an integer res equal to the integer Maximum.
- Run a for loop from i equal to 1 till i is less than or equal to k.
- Set curr equal to maximum of eggDrop(n-1, i-1) or eggDrop(n, k-i).
- If curr is less than res then set res equal to curr.
- Return res
C++ #include <bits/stdc++.h> using namespace std; // Function to find minimum number of attempts // needed in order to find the critical floor int eggDrop(int n, int k) { // if there is less than or equal to one floor if (k == 1 || k == 0) return k; // if there is only one egg if (n == 1) return k; // to store the minimum number of attempts int res = INT_MAX; // Consider all droppings from // 1st floor to kth floor for (int i = 1; i <= k; i++) { int cur = 1 + max(eggDrop(n - 1, i - 1), eggDrop(n, k - i)); if (cur < res) res = cur; } return res; } int main() { int n = 2, k = 10; cout << eggDrop(n, k); return 0; }
Java // Function to find minimum number of attempts // needed in order to find the critical floor import java.util.*; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // if there is less than or equal to one floor if (k == 1 || k == 0) return k; // if there is only one egg if (n == 1) return k; // to store the minimum number of attempts int res = Integer.MAX_VALUE; // Consider all droppings from // 1st floor to kth floor for (int i = 1; i <= k; i++) { int cur = 1 + Math.max(eggDrop(n - 1, i - 1), eggDrop(n, k - i)); if (cur < res) res = cur; } return res; } public static void main(String[] args) { int n = 2, k = 10; System.out.println(eggDrop(n, k)); } }
Python # Function to find minimum number of attempts # needed in order to find the critical floor def eggDrop(n, k): # if there is less than or equal to one floor if k == 1 or k == 0: return k # if there is only one egg if n == 1: return k # to store the minimum number of attempts res = float('inf') # Consider all droppings from # 1st floor to kth floor for i in range(1, k + 1): cur = 1 + max(eggDrop(n - 1, i - 1), eggDrop(n, k - i)) if cur < res: res = cur return res if __name__ == "__main__": n = 2 k = 10 print(eggDrop(n, k))
C# // Function to find minimum number of attempts // needed in order to find the critical floor using System; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // if there is less than or equal to one floor if (k == 1 || k == 0) return k; // if there is only one egg if (n == 1) return k; // to store the minimum number of attempts int res = int.MaxValue; // Consider all droppings from // 1st floor to kth floor for (int i = 1; i <= k; i++) { int cur = 1 + Math.Max(eggDrop(n - 1, i - 1), eggDrop(n, k - i)); if (cur < res) res = cur; } return res; } static void Main() { int n = 2, k = 10; Console.WriteLine(eggDrop(n, k)); } }
JavaScript // Function to find minimum number of attempts // needed in order to find the critical floor function eggDrop(n, k) { // if there is less than or equal to one floor if (k === 1 || k === 0) return k; // if there is only one egg if (n === 1) return k; // to store the minimum number of attempts let res = Number.MAX_SAFE_INTEGER; // Consider all droppings from // 1st floor to kth floor for (let i = 1; i <= k; i++) { let cur = 1 + Math.max(eggDrop(n - 1, i - 1), eggDrop(n, k - i)); if (cur < res) res = cur; } return res; } let n = 2, k = 10; console.log(eggDrop(n, k));
Analyzing the Overlapping Subproblems in Egg Dropping Puzzle
In the recursive solution, many subproblems are computed more than once. Consider calculating the number of attempts for 2 eggs and 10 floors.
When dropping an egg from a certain floor i, the problem divides into two subproblems:
- one for the floors below (eggDrop(1, i-1))
- one for the floors above (eggDrop(2, 10-i)).
Different choices of i can lead to the same subproblem being solved multiple times (for example, eggDrop(2, 3) might be computed in several different branches).
This repeated computation of the same subproblems demonstrates overlapping subproblems, which makes memoization a highly effective optimisation technique.
[Better Approach] Using Memoization - O(n * k^2) Time and O(n * k) Space
The above approach can be optimized using memoization, as we are computing the same sub-problem multiple times.
- The idea is to create a 2d array memo[][] of order n * k, to store the results of the sub-problem, where memo[i][j] stores the result of i eggs and j floors.
- For each recursive call, check if the value is already computed, if so, return the stored value, else proceed similar to the above approach, and at last store the results in memo[][] and return the value.
C++ #include <bits/stdc++.h> using namespace std; // Function to find minimum number of attempts // needed in order to find the critical floor int solveEggDrop(int n, int k, vector<vector<int>> &memo) { // if value is already calculated if (memo[n][k] != -1) { return memo[n][k]; } // if there is less than or equal to one floor if (k == 1 || k == 0) return k; // if there is only one egg if (n == 1) return k; // to store the minimum number of attempts int res = INT_MAX; // Consider all droppings from // 1st floor to kth floor for (int i = 1; i <= k; i++) { int cur = max(solveEggDrop(n - 1, i - 1, memo), solveEggDrop(n, k - i, memo)); if (cur < res) res = cur; } // update the memo, and return return memo[n][k] = res + 1; } // Function to find minimum number of attempts // needed in order to find the critical floor int eggDrop(int n, int k) { // create memo table vector<vector<int>> memo(n + 1, vector<int>(k + 1, -1)); return solveEggDrop(n, k, memo); } int main() { int n = 2, k = 10; cout << eggDrop(n, k); return 0; }
Java // Function to find minimum number of attempts // needed in order to find the critical floor import java.util.*; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int solveEggDrop(int n, int k, int[][] memo) { // if value is already calculated if (memo[n][k] != -1) { return memo[n][k]; } // if there is less than or equal to one floor if (k == 1 || k == 0) return k; // if there is only one egg if (n == 1) return k; // to store the minimum number of attempts int res = Integer.MAX_VALUE; // Consider all droppings from // 1st floor to kth floor for (int i = 1; i <= k; i++) { int cur = Math.max(solveEggDrop(n - 1, i - 1, memo), solveEggDrop(n, k - i, memo)); if (cur < res) res = cur; } // update the memo, and return memo[n][k] = res + 1; return memo[n][k]; } // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // create memo table int[][] memo = new int[n + 1][k + 1]; for (int i = 0; i <= n; i++) { Arrays.fill(memo[i], -1); } return solveEggDrop(n, k, memo); } public static void main(String[] args) { int n = 2, k = 10; System.out.println(eggDrop(n, k)); } }
Python # Function to find minimum number of attempts # needed in order to find the critical floor def solveEggDrop(n, k, memo): # if value is already calculated if memo[n][k] != -1: return memo[n][k] # if there is less than or equal to one floor if k == 1 or k == 0: return k # if there is only one egg if n == 1: return k # to store the minimum number of attempts res = float('inf') # Consider all droppings from # 1st floor to kth floor for i in range(1, k + 1): cur = max(solveEggDrop(n - 1, i - 1, memo), \ solveEggDrop(n, k - i, memo)) if cur < res: res = cur # update the memo, and return memo[n][k] = res + 1 return memo[n][k] # Function to find minimum number of attempts # needed in order to find the critical floor def eggDrop(n, k): # create memo table memo = [[-1 for _ in range(k + 1)] for _ in range(n + 1)] return solveEggDrop(n, k, memo) if __name__ == "__main__": n = 2 k = 10 print(eggDrop(n, k))
C# // Function to find minimum number of attempts // needed in order to find the critical floor using System; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int solveEggDrop(int n, int k, int[][] memo) { // if value is already calculated if (memo[n][k] != -1) return memo[n][k]; // if there is less than or equal to one floor if (k == 1 || k == 0) return k; // if there is only one egg if (n == 1) return k; // to store the minimum number of attempts int res = int.MaxValue; // Consider all droppings from // 1st floor to kth floor for (int i = 1; i <= k; i++) { int cur = Math.Max(solveEggDrop(n - 1, i - 1, memo), solveEggDrop(n, k - i, memo)); if (cur < res) res = cur; } // update the memo, and return memo[n][k] = res + 1; return memo[n][k]; } // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // create memo table int[][] memo = new int[n + 1][]; for (int i = 0; i <= n; i++) { memo[i] = new int[k + 1]; for (int j = 0; j <= k; j++) { memo[i][j] = -1; } } return solveEggDrop(n, k, memo); } static void Main() { int n = 2, k = 10; Console.WriteLine(eggDrop(n, k)); } }
JavaScript // Function to find minimum number of attempts // needed in order to find the critical floor function solveEggDrop(n, k, memo) { // if value is already calculated if (memo[n][k] !== -1) return memo[n][k]; // if there is less than or equal to one floor if (k === 1 || k === 0) return k; // if there is only one egg if (n === 1) return k; // to store the minimum number of attempts let res = Number.MAX_SAFE_INTEGER; // Consider all droppings from // 1st floor to kth floor for (let i = 1; i <= k; i++) { let cur = Math.max(solveEggDrop(n - 1, i - 1, memo), solveEggDrop(n, k - i, memo)); if (cur < res) res = cur; } // update the memo, and return memo[n][k] = res + 1; return memo[n][k]; } // Function to find minimum number of attempts // needed in order to find the critical floor function eggDrop(n, k) { // create memo table let memo = new Array(n + 1); for (let i = 0; i <= n; i++) { memo[i] = new Array(k + 1).fill(-1); } return solveEggDrop(n, k, memo); } // Driver code let n = 2, k = 10; console.log(eggDrop(n, k));
[Expected Approach] Using Tabulation with Optimization - O(n * k) Time and O(n * k) Space
A direct tabulation based solution for the above memoization and recursive approach would require O(n * k^2) Time and O(n * k) Space. We can further optimize the above approach.
In the above approach, each state memo[i][j] stores the number of moves required to solve the sub-problem of i eggs and j floors. Instead of doing so, the idea is to make dp[i][j] store the maximum number of floors that can be processed using i moves and j eggs. By doing so, we will only be required to find the maximum reachable floor in the previous move, and will avoid checking each k floor for all the states.
Step-by-step approach:
- Create a 2d table dp[][] of order k * n (as k is the maximum possible moves required).
- Initialize the counter cnt to store the number of moves.
- Run a while loop until the number of floors i.e. dp[cnt][n] is less than k.
- At each iteration increment the moves by 1 (i.e. increment cnt by 1), and run a loop from 1 to n, representing the number of eggs.
- At each iteration, there are two possibilities:
- If egg breaks, then check the result of dp[cnt - 1][i - 1].
- If egg doesn't break, then check the result of dp[cnt - 1][i].
- Update dp[cnt][i] = 1 + dp[cnt - 1][i - 1] + dp[cnt - 1][i], where we are adding 1 for the current floor.
- At last return the count of moves cnt.
C++ #include <bits/stdc++.h> using namespace std; // Function to find minimum number of attempts // needed in order to find the critical floor int eggDrop(int n, int k) { // create a 2D table to store the results vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0)); // to count the number of moves int cnt = 0; // while the number of floors is less than k while (dp[cnt][n] < k) { cnt++; // for each egg for (int i = 1; i <= n; i++) { dp[cnt][i] = 1 + dp[cnt - 1][i - 1] + dp[cnt - 1][i]; } } return cnt; } int main() { int n = 2, k = 10; cout << eggDrop(n, k); return 0; }
Java // Function to find minimum number of attempts // needed in order to find the critical floor import java.util.*; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // create a 2D table to store the results int[][] dp = new int[k + 1][n + 1]; // to count the number of moves int cnt = 0; // while the number of floors is less than k while (dp[cnt][n] < k) { cnt++; // for each egg for (int i = 1; i <= n; i++) { dp[cnt][i] = 1 + dp[cnt - 1][i - 1] + dp[cnt - 1][i]; } } return cnt; } public static void main(String[] args) { int n = 2, k = 10; System.out.println(eggDrop(n, k)); } }
Python # Function to find minimum number of attempts # needed in order to find the critical floor def eggDrop(n, k): # create a 2D table to store the results dp = [[0 for _ in range(n + 1)] for _ in range(k + 1)] # to count the number of moves cnt = 0 # while the number of floors is less than k while dp[cnt][n] < k: cnt += 1 # for each egg for i in range(1, n + 1): dp[cnt][i] = 1 + dp[cnt - 1][i - 1] + dp[cnt - 1][i] return cnt if __name__ == "__main__": n = 2 k = 10 print(eggDrop(n, k))
C# // Function to find minimum number of attempts // needed in order to find the critical floor using System; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // create a 2D table to store the results int[][] dp = new int[k + 1][]; for (int i = 0; i <= k; i++) { dp[i] = new int[n + 1]; } // to count the number of moves int cnt = 0; // while the number of floors is less than k while (dp[cnt][n] < k) { cnt++; // for each egg for (int i = 1; i <= n; i++) { dp[cnt][i] = 1 + dp[cnt - 1][i - 1] + dp[cnt - 1][i]; } } return cnt; } static void Main() { int n = 2, k = 10; Console.WriteLine(eggDrop(n, k)); } }
JavaScript // Function to find minimum number of attempts // needed in order to find the critical floor function eggDrop(n, k) { // create a 2D table to store the results let dp = new Array(k + 1); for (let i = 0; i <= k; i++) { dp[i] = new Array(n + 1).fill(0); } // to count the number of moves let cnt = 0; // while the number of floors is less than k while (dp[cnt][n] < k) { cnt++; // for each egg for (let i = 1; i <= n; i++) { dp[cnt][i] = 1 + dp[cnt - 1][i - 1] + dp[cnt - 1][i]; } } return dp[cnt][n] >= k ? cnt : cnt; } let n = 2, k = 10; console.log(eggDrop(n, k));
[Optimized Approach] Using Space-Optimized Table - O(n * k) Time and O(n) Space
In the above approach, to calculate the current row of the dp[][] table, we require only the previous row results. The idea is to create a 1D array dp[] of size n to store the result for each move. To do so, proceed similar to above approach, and for each iteration, set dp[i] = 1 + dp[i] + dp[i-1]. At last return the value stored in dp[n].
Illustration for 2 Eggs and 10 Floors (n = 2, k = 10)
C++ #include <bits/stdc++.h> using namespace std; // Function to find minimum number of attempts // needed in order to find the critical floor int eggDrop(int n, int k) { // create an array to store the results vector<int> dp(n + 1, 0); // to count the number of moves int cnt = 0; // while the number of floors is less than k while (dp[n] < k) { cnt++; // for each egg for (int i = n; i > 0; i--) { dp[i] += 1 + dp[i - 1]; } } return cnt; } int main() { int n = 2, k = 10; cout << eggDrop(n, k); return 0; }
Java // Function to find minimum number of attempts // needed in order to find the critical floor import java.util.*; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // create an array to store the results int[] dp = new int[n + 1]; // to count the number of moves int cnt = 0; // while the number of floors is less than k while (dp[n] < k) { cnt++; // for each egg for (int i = n; i > 0; i--) { dp[i] += 1 + dp[i - 1]; } } return cnt; } public static void main(String[] args) { int n = 2, k = 10; System.out.println(eggDrop(n, k)); } }
Python # Function to find minimum number of attempts # needed in order to find the critical floor def eggDrop(n, k): # create an array to store the results dp = [0] * (n + 1) # to count the number of moves cnt = 0 # while the number of floors is less than k while dp[n] < k: cnt += 1 # for each egg for i in range(n, 0, -1): dp[i] += 1 + dp[i - 1] return cnt if __name__ == "__main__": n = 2 k = 10 print(eggDrop(n, k))
C# // Function to find minimum number of attempts // needed in order to find the critical floor using System; class GfG { // Function to find minimum number of attempts // needed in order to find the critical floor static int eggDrop(int n, int k) { // create an array to store the results int[] dp = new int[n + 1]; // to count the number of moves int cnt = 0; // while the number of floors is less than k while (dp[n] < k) { cnt++; // for each egg for (int i = n; i > 0; i--) { dp[i] += 1 + dp[i - 1]; } } return cnt; } static void Main() { int n = 2, k = 10; Console.WriteLine(eggDrop(n, k)); } }
JavaScript // Function to find minimum number of attempts // needed in order to find the critical floor function eggDrop(n, k) { // create an array to store the results let dp = new Array(n + 1).fill(0); // to count the number of moves let cnt = 0; // while the number of floors is less than k while (dp[n] < k) { cnt++; // for each egg for (let i = n; i > 0; i--) { dp[i] += 1 + dp[i - 1]; } } return cnt; } let n = 2, k = 10; console.log(eggDrop(n, k));
Related Articles:
Similar Reads
Dynamic Programming or DP Dynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
What is Memoization? A Complete Tutorial In this tutorial, we will dive into memoization, a powerful optimization technique that can drastically improve the performance of certain algorithms. Memoization helps by storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids redundant calcula
6 min read
Dynamic Programming (DP) Introduction Dynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again.The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way t
15+ min read
Tabulation vs Memoization Tabulation and memoization are two techniques used to implement dynamic programming. Both techniques are used when there are overlapping subproblems (the same subproblem is executed multiple times). Below is an overview of two approaches.Memoization:Top-down approachStores the results of function ca
9 min read
Optimal Substructure Property in Dynamic Programming | DP-2 The following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property. Let us discuss the Optimal Substructure property here.
3 min read
Overlapping Subproblems Property in Dynamic Programming | DP-1 Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem
10 min read
Steps to solve a Dynamic Programming Problem Steps to solve a Dynamic programming problem:Identify if it is a Dynamic programming problem.Decide a state expression with the Least parameters.Formulate state and transition relationship.Apply tabulation or memorization.Step 1: How to classify a problem as a Dynamic Programming Problem? Typically,
13 min read
Advanced Topics
Count Ways To Assign Unique Cap To Every PersonGiven n people and 100 types of caps labelled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps.Example:Input: caps = [[3, 4], [4, 5], [5]] Output:
15+ min read
Digit DP | IntroductionPrerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers 'x' between two integers say 'a' and 'b' such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such intege
14 min read
Sum over Subsets | Dynamic ProgrammingPrerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bit
10 min read
Easy problems in Dynamic programming
Coin Change - Count Ways to Make SumGiven an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
15+ min read
Subset Sum ProblemGiven an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. Examples: Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9.Input: arr[] = [3, 34, 4
15+ min read
Introduction and Dynamic Programming solution to compute nCr%pGiven three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is
15+ min read
Rod CuttingGiven a rod of length n inches and an array price[]. price[i] denotes the value of a piece of length i. The task is to determine the maximum value obtainable by cutting up the rod and selling the pieces.Note: price[] is 1-indexed array.Input: price[] = [1, 5, 8, 9, 10, 17, 17, 20]Output: 22Explanati
15+ min read
Painting Fence AlgorithmGiven a fence with n posts and k colors, the task is to find out the number of ways of painting the fence so that not more than two consecutive posts have the same color.Examples:Input: n = 2, k = 4Output: 16Explanation: We have 4 colors and 2 posts.Ways when both posts have same color: 4 Ways when
15 min read
Longest Common Subsequence (LCS)Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
15+ min read
Longest Increasing Subsequence (LIS)Given an array arr[] of size n, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order.Examples: Input: arr[] = [3, 10, 2, 1, 20]Output: 3Explanation: The longest increa
14 min read
Longest subsequence such that difference between adjacents is oneGiven an array arr[] of size n, the task is to find the longest subsequence such that the absolute difference between adjacent elements is 1.Examples: Input: arr[] = [10, 9, 4, 5, 4, 8, 6]Output: 3Explanation: The three possible subsequences of length 3 are [10, 9, 8], [4, 5, 4], and [4, 5, 6], wher
15+ min read
Maximum size square sub-matrix with all 1sGiven a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s.Example:Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ]Output: 3Explanation: The maximum length of a
15+ min read
Min Cost PathYou are given a 2D matrix cost[][] of dimensions m à n, where each cell represents the cost of traversing through that position. Your goal is to determine the minimum cost required to reach the bottom-right cell (m-1, n-1) starting from the top-left cell (0,0).The total cost of a path is the sum of
15+ min read
Longest Common Substring (Space optimized DP solution)Given two strings âs1â and âs2â, find the length of the longest common substring. Example: Input: s1 = âGeeksforGeeksâ, s2 = âGeeksQuizâ Output : 5 Explanation:The longest common substring is âGeeksâ and is of length 5.Input: s1 = âabcdxyzâ, s2 = âxyzabcdâ Output : 4Explanation:The longest common su
7 min read
Count ways to reach the nth stair using step 1, 2 or 3A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs.Examples: Input: 4Output: 7Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1},
15+ min read
Grid Unique Paths - Count Paths in matrixGiven an matrix of size m x n, the task is to find the count of all unique possible paths from top left to the bottom right with the constraints that from each cell we can either move only to the right or down.Examples: Input: m = 2, n = 2Output: 2Explanation: There are two paths(0, 0) -> (0, 1)
15+ min read
Unique paths in a Grid with ObstaclesGiven a matrix mat[][] of size n * m, where mat[i][j] = 1 indicates an obstacle and mat[i][j] = 0 indicates an empty space. The task is to find the number of unique paths to reach (n-1, m-1) starting from (0, 0). You are allowed to move in the right or downward direction. Note: In the grid, cells ma
15+ min read
Medium problems on Dynamic programming
0/1 Knapsack ProblemGiven n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
15+ min read
Printing Items in 0/1 KnapsackGiven weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
12 min read
Unbounded Knapsack (Repetition of items allowed)Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
15+ min read
Egg Dropping Puzzle | DP-11You are given n identical eggs and you have access to a k-floored building from 1 to k.There exists a floor f where 0 <= f <= k such that any egg dropped from a floor higher than f will break, and any egg dropped from or below floor f will not break. There are a few rules given below:An egg th
15+ min read
Word BreakGiven a string s and y a dictionary of n words dictionary, check if s can be segmented into a sequence of valid words from the dictionary, separated by spaces.Examples:Input: s = "ilike", dictionary[] = ["i", "like", "gfg"]Output: trueExplanation: The string can be segmented as "i like".Input: s = "
12 min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either âuâ or âvâ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complet
15+ min read
Tile Stacking ProblemGiven integers n (the height of the tower), m (the maximum size of tiles available), and k (the maximum number of times each tile size can be used), the task is to calculate the number of distinct stable towers of height n that can be built. Note:A stable tower consists of exactly n tiles, each stac
15+ min read
Box Stacking ProblemGiven three arrays height[], width[], and length[] of size n, where height[i], width[i], and length[i] represent the dimensions of a box. The task is to create a stack of boxes that is as tall as possible, but we can only stack a box on top of another box if the dimensions of the 2-D base of the low
15+ min read
Partition a Set into Two Subsets of Equal SumGiven an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.Note: Each element is present in either the first subset or the second subset, but not in both.Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: Th
15+ min read
Travelling Salesman Problem using Dynamic ProgrammingGiven a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost.Note the difference
15 min read
Longest Palindromic Subsequence (LPS)Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Longest Palindromic SubsequenceExamples:Input: s = "bbabcbcab"Output: 7Explanation: Subsequen
15+ min read
Longest Common Increasing Subsequence (LCS + LIS)Given two arrays, a[] and b[], find the length of the longest common increasing subsequence(LCIS). LCIS refers to a subsequence that is present in both arrays and strictly increases.Prerequisites: LCS, LIS.Examples:Input: a[] = [3, 4, 9, 1], b[] = [5, 3, 8, 9, 10, 2, 1]Output: 2Explanation: The long
15+ min read
Find all distinct subset (or subsequence) sums of an arrayGiven an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small.Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
15+ min read
Weighted Job SchedulingGiven a 2D array jobs[][] of order n*3, where each element jobs[i] defines start time, end time, and the profit associated with the job. The task is to find the maximum profit you can take such that there are no two jobs with overlapping time ranges.Note: If the job ends at time X, it is allowed to
15+ min read
Count Derangements (Permutation such that no element appears in its original position)A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of [0, 1, 2, 3] is [2, 3, 1, 0].Given a number n, find the total number of Derangements of a set of n elements.Examples : Input: n = 2Output: 1Explanation: For two balls [1
12 min read
Minimum insertions to form a palindromeGiven a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome.Examples:Input: s = "geeks"Output: 3Explanation: "skgeegks" is a palindromic string, which requires 3 insertions.Input: s= "abcd"Output: 3Explanation: "abcdcba" is a palindromic string
15+ min read
Ways to arrange Balls such that adjacent balls are of different typesThere are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of the same type are adjacent.Examples : Input: p = 1, q = 1, r = 0Output: 2Explanation: There are only two arrangements PQ and QPInput: p = 1, q = 1,
15+ min read