chapter

    Dynamic Programming, Greedy Algorithms and Optimization Pyqs for Gate Cs

    Solve 5+ Dynamic Programming, Greedy Algorithms and Optimization previous year questions for GATE CS with answers and detailed solutions. Free sample question

    Try a question

    Answer it here to see how it works. Nothing is recorded until you sign in.

    Question 1
    2026 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider a table , where the elements , , represent the cost of the optimal solutions of different subproblems of a problem that is being solved using a dynamic programming algorithm. The recursive formulation to compute the table entries is as follows:



    Consider the following two algorithms to compute entries of . Assume that for both the algorithms, for all , has been initialized to .

    Algorithm : For
        For
            

    Algorithm : For
        For
            For
                If
                    

    Algorithm , is said to be correct if and only if it calculates the correct values of , for all , (as per the recursive formulation) at the end of the execution of the algorithm .

    Which one of the following statements is true?
    Question 2
    2024 Slot Set2 PYQ
    Level 3: Exam Standard

    Let be an array containing integer values. The distance of is defined as the minimum number of elements in that must be replaced with another integer so that the resulting array is sorted in non-decreasing order. The distance of the array is ___________

    Question 3
    2021 Slot Set2 PYQ
    Level 3: Exam Standard
    In a directed acyclic graph with a source vertex , the quality-score of a directed path is defined to be the product of the weights of the edges on the path. Further, for a vertex other than , the quality-score of is defined to be the maximum among the quality-scores of all the paths from to . The quality-score of is assumed to be 1.

    s a b c d e f g t 9 1 1 9 1 1 1 9 1 9 1 9
    The sum of the quality-scores of all the vertices in the graph shown above is __________.
    Question 4
    2021 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider the string abbccddeee. Each letter in the string must be assigned a binary code satisfying the following properties:

    1. For any two letters, the code assigned to one letter must not be a prefix of the code assigned to the other letter.
    2. For any two letters of the same frequency, the letter which occurs earlier in the dictionary order is assigned a code whose length is at most the length of the code assigned to the other letter.

    Among the set of all binary code assignments which satisfy the above two properties, what is the minimum length of the encoded string?
    Question 5
    2021 Slot Set1 PYQ
    Level 3: Exam Standard
    Define to be the maximum amount earned by cutting a rod of length meters into one or more pieces of integer length and selling them. For , let denote the selling price of a rod whose length is meters. Consider the array of prices:


    Which of the following statements is/are correct about ?
    Free preview ends here

    Login to view the complete previous-year questions and solutions

    Creating an account is free. You get the rest of this chapter, step-by-step solutions, and a study plan built around the topics you are actually weak at.

    Explore complete test series, official past papers, and chapter-wise study tools.

    Why MastersUp

    Personalised first. High quality throughout.

    Most platforms hand everyone the same content. Here the content moves with your performance, topic by topic.

    Built around you, not around a syllabus PDF

    Every answer you give moves your topic-level intelligence rate. The next question, the next revision card and tomorrow's plan all change with it.

    Revision that hits your weak spots

    We only revise topics you have actually attempted and are still below the safe bar on — never the same chapter on repeat.

    Questions calibrated to the real exam

    Each question carries a measured toughness. You are served a rung above your current level, so practice keeps stretching you.

    Notes written for recall, not for volume

    Full lesson cards for first study, curated short-note cards for the last mile — with derivations, traps and exam patterns marked.

    One place for everything

    Notes, chapter practice, previous-year questions, test series and full-length papers — all feeding one picture of your preparation.

    Honest progress

    No vanity streaks. Progress here means chapters mastered and accuracy that held up on harder questions.

    Unlock the whole course

    Full notes and short notes, the complete question bank with worked solutions, mock tests, full-length papers, and an adaptive plan that rebuilds itself as you improve.

    Dynamic Programming, Greedy Algorithms and Optimization PYQs for GATE CS

    Solve 5+ Dynamic Programming, Greedy Algorithms and Optimization previous year questions for GATE CS with answers and detailed solutions. Free sample questions below.

    Chapter Roadmap: Counting and Combinatorics

    Chapter Roadmap

    Counting & Combinatorics

    School Level Mathematics · Data Science

    1
    Selection Intuition
    Understand when order does not matter.
    You are here
    2
    Core Tool: The Choose Formula
    Count unordered groups without listing them.
    3
    Exam Methods
    Apply the formula to multiple groups, categories, and conditions.
    4
    Constraints & Traps
    Handle "at least", "at most", fixed items, and overcounting.
    5
    Exam Readiness
    Final checklist to choose the correct method quickly.
    By the end: You will count unordered selections from distinct groups, apply multiplication and addition rules correctly, and solve constrained selection problems confidently.

    What is a Combination?

    Concept · Level 1

    What is a Combination?

    In counting problems, most questions ask you to either arrange objects or select objects.

    Selection
    Only who or what is in the group matters.
    Arrangement
    Both the members and their order matter.
    The Swap Test
    Ask: "If I swap two chosen items, does the outcome change?"
    No → Combination   |   Yes → Arrangement
    Example
    Selecting 3 questions out of 5 to answer on a paper: choosing questions 1, 2, 3 is the same as choosing 3, 2, 1. The set of attempted questions is unchanged. This is a combination.

    Dynamic Programming, Greedy Algorithms and Optimization: Solved Questions with Step-by-Step Explanations (5 Problems)

    Question 1 · Algorithms · 2026_Set2 MCQ
    Consider a table , where the elements , , represent the cost of the optimal solutions of different subproblems of a problem that is being solved using a dynamic programming algorithm. The recursive formulation to compute the table entries is as follows:



    Consider the following two algorithms to compute entries of . Assume that for both the algorithms, for all , has been initialized to .

    Algorithm : For
        For
            

    Algorithm : For
        For
            For
                If
                    

    Algorithm , is said to be correct if and only if it calculates the correct values of , for all , (as per the recursive formulation) at the end of the execution of the algorithm .

    Which one of the following statements is true?
    1. A.

      Both algorithms and are correct

    2. B.

      Algorithm is correct, but algorithm is incorrect

    3. C.

      Algorithm is correct, but algorithm is incorrect

    4. D.

      Both algorithms and are incorrect

    Correct Answer:

    A

    Step-by-Step Solution

    Insight: DP table evaluation is correct if and only if every cell's dependencies are fully computed before the cell itself is evaluated.

    Exam route: Check Algorithm B1 (row-major) and B2 (diagonal) against the dependency rule for T[i][j] = 2T[i-1][j] + 3T[i][j-1].

    Learning route:

    The recurrence requires T[i-1][j] (previous row) and T[i][j-1] (same row, previous column).

    Algorithm B1 uses nested loops: outer i from 1 to n, inner j from 1 to n. When computing T[i][j], row i-1 is already complete, and in row i, column j-1 is already complete. This satisfies the dependency rule.

    Algorithm B2 iterates by the sum of indices s = i + j from 2 to 2n. For any cell T[i][j] with sum s, its dependencies T[i-1][j] and T[i][j-1] both have an index sum of (i-1)+j = s-1 and i+(j-1) = s-1. Since the outer loop processes all cells with sum s-1 before any cell with sum s, all dependencies are guaranteed to be resolved.

    Both algorithms are mathematically correct.

    Question 2 · Algorithms · 2024_Set2 NAT

    Let be an array containing integer values. The distance of is defined as the minimum number of elements in that must be replaced with another integer so that the resulting array is sorted in non-decreasing order. The distance of the array is ___________

    Correct Answer:

    3.00

    Step-by-Step Solution

    Insight: The minimum number of replacements to sort an array equals the total array length minus the length of its Longest Non-Decreasing Subsequence (LNDS).

    Exam route: Find the LNDS of [2, 5, 3, 1, 4, 2, 6]. The LNDS is [2, 3, 4, 6] (length 4). Distance = 7 - 4 = 3.

    Learning route:

    To minimize replacements, we must maximize the number of elements we keep. The elements we keep must already be in non-decreasing order, meaning they must form a Non-Decreasing Subsequence.

    Let's find the LNDS of A = [2, 5, 3, 1, 4, 2, 6]:

    • Start with 2 (index 0).
    • Next valid is 3 (index 2).
    • Next valid is 4 (index 4).
    • Next valid is 6 (index 6).

    This gives the subsequence [2, 3, 4, 6], which has length 4.

    Can we find a longer one?

    • [2, 5, 6] has length 3.
    • [1, 2, 6] has length 3.
    • [1, 4, 6] has length 3.

    The maximum length of a non-decreasing subsequence is indeed 4.

    Therefore, the minimum number of elements to replace is Total Length - LNDS Length = 7 - 4 = 3.

    (For example, replace 5 with 2, 1 with 3, and 2 with 5 to get [2, 2, 3, 3, 4, 5, 6]).

    Question 3 · Algorithms · 2021_Set2 NAT
    In a directed acyclic graph with a source vertex , the quality-score of a directed path is defined to be the product of the weights of the edges on the path. Further, for a vertex other than , the quality-score of is defined to be the maximum among the quality-scores of all the paths from to . The quality-score of is assumed to be 1.

    s a b c d e f g t 9 1 1 9 1 1 1 9 1 9 1 9
    The sum of the quality-scores of all the vertices in the graph shown above is __________.
    Correct Answer:

    929.00

    Step-by-Step Solution

    Insight: In a DAG, the maximum product path to a vertex v is the maximum over all predecessors u of (OPT(u) * weight(u, v)).

    Exam route: Compute OPT for each vertex in topological order: s, c, f, a, d, g, b, e, t. Sum all OPT values at the end.

    Learning route:

    We evaluate vertices in topological order to ensure all predecessors are resolved. Base case: OPT(s) = 1. All others initialized to 0 (since weights are positive and we want max product).

    1. OPT(s) = 1
    2. OPT(c) = OPT(s) * 1 = 1
    3. OPT(a) = OPT(s) * 9 = 9
    4. OPT(f) = OPT(c) 9 = 1 9 = 9
    5. OPT(d) = max(OPT(c)1, OPT(a)1) = max(11, 91) = 9
    6. OPT(b) = OPT(a) 1 = 9 1 = 9
    7. OPT(g) = max(OPT(f)1, OPT(d)9) = max(91, 99) = max(9, 81) = 81
    8. OPT(e) = max(OPT(d)9, OPT(b)1) = max(99, 91) = max(81, 9) = 81
    9. OPT(t) = max(OPT(g)1, OPT(e)9) = max(811, 819) = max(81, 729) = 729

    Sum of all quality-scores = OPT(s)+OPT(c)+OPT(a)+OPT(f)+OPT(d)+OPT(b)+OPT(g)+OPT(e)+OPT(t)

    Sum = 1 + 1 + 9 + 9 + 9 + 9 + 81 + 81 + 729 = 929.

    Question 4 · Algorithms · 2021_Set2 MCQ
    Consider the string abbccddeee. Each letter in the string must be assigned a binary code satisfying the following properties:

    1. For any two letters, the code assigned to one letter must not be a prefix of the code assigned to the other letter.
    2. For any two letters of the same frequency, the letter which occurs earlier in the dictionary order is assigned a code whose length is at most the length of the code assigned to the other letter.

    Among the set of all binary code assignments which satisfy the above two properties, what is the minimum length of the encoded string?
    1. A.

      21

    2. B.

      23

    3. C.

      25

    4. D.

      30

    Correct Answer:

    B

    Step-by-Step Solution

    Insight: Huffman coding minimizes total length, but when frequencies tie, the tree structure must be chosen to satisfy the lexicographical length constraint.

    Exam route: Frequencies are a:1, b:2, c:2, d:2, e:3. The constraint requires length(b) ≤ length(c) ≤ length(d). We must merge carefully to keep b and c higher in the tree than d.

    Learning route:

    Standard greedy merging might pair a(1) with b(2), and c(2) with d(2), yielding lengths: a:3, b:3, c:2, d:2. This violates length(b) ≤ length(c) because 3 is not ≤ 2.

    To satisfy the constraint, we must avoid merging b early. Instead, merge the smallest available that doesn't violate the rule: merge a(1) with d(2) to form ad(3).

    Remaining nodes: b(2), c(2), e( spadesuit wait, e is 3), ad(3).

    Next, merge the two smallest: b(2) and c(2) to form bc(4).

    Remaining: e(3), ad(3), bc(4).

    Merge e(3) and ad(3) to form e-ad(6).

    Finally, merge bc(4) and e-ad(6) to form Root(10).

    Let's check the depths (code lengths):

    • bc is a child of Root (depth 1), so b and c have depth 2.
    • e-ad is a child of Root (depth 1), so e has depth 2, and ad has depth 2.
    • ad has depth 2, so a and d have depth 3.

    Lengths: a:3, b:2, c:2, d:3, e:2.

    Check constraint: length(b)=2 ≤ length(c)=2 ≤ length(d)=3. This is valid.

    Total encoded length = (1×3) + (2×2) + (2×2) + (2×3) + (3×2) = 3 + 4 + 4 + 6 + 6 = 23 bits.

    Question 5 · Algorithms · 2021_Set1 MSQ
    Define to be the maximum amount earned by cutting a rod of length meters into one or more pieces of integer length and selling them. For , let denote the selling price of a rod whose length is meters. Consider the array of prices:


    Which of the following statements is/are correct about ?
    1. A.

    2. B.

    3. C.

      is achieved by three different solutions.

    4. D.

      cannot be achieved by a solution consisting of three pieces.

    Correct Answer:

    ["A","C"]

    Step-by-Step Solution

    Insight: Rod cutting is an unbounded knapsack problem. We compute the max revenue R_i for each length i up to 7, then enumerate the partitions that achieve R_7.

    Exam route: Compute R_1 to R_7. R_1=1, R_2=5, R_3=8, R_4=10, R_5=13, R_6=17, R_7=18. Check which partitions of 7 yield 18.

    Learning route:

    We use the recurrence: R_j = max(p[i] + R_{j-i}) for 1 i j.

    • R_1 = p[1] = 1
    • R_2 = max(p[2], R_1+R_1) = max(5, 2) = 5
    • R_3 = max(p[3], R_1+R_2, R_2+R_1) = max(8, 1+5, 5+1) = 8
    • R_4 = max(p[4], R_1+R_3, R_2+R_2) = max(9, 1+8, 5+5) = 10 (achieved by two pieces of length 2)
    • R_5 = max(p[5], R_1+R_4, R_2+R_3) = max(10, 1+10, 5+8) = 13 (achieved by lengths 2 and 3)
    • R_6 = max(p[6], R_1+R_5, R_2+R_4, R_3+R_3) = max(17, 1+13, 5+10, 8+8) = max(17, 14, 15, 16) = 17 (achieved by uncut length 6)
    • R_7 = max(p[7], R_1+R_6, R_2+R_5, R_3+R_4) = max(18, 1+17, 5+13, 8+10) = max(18, 18, 18, 18) = 18.

    So, R_7 = 18. (Option A is correct, B is incorrect).

    Now, find all distinct partitions of 7 that yield 18:

    1. {7} p[7] = 18
    2. {6, 1} p[6] + R_1 = 17 + 1 = 18
    3. {3, 2, 2} p[3] + p[2] + p[2] = 8 + 5 + 5 = 18

    Are there any others? {4, 3} yields 9+8=17. {5, 2} yields 10+5=15. {4, 2, 1} yields 9+5+1=15. {3, 3, 1} yields 8+8+1=17.

    Thus, exactly 3 different solutions (partitions) achieve the maximum revenue. (Option C is correct).

    Since {3, 2, 2} consists of three pieces, Option D is incorrect.

    More previous year questions (pyqs) in this unit