GATE / CS ARCHIVE

SUBJECT COLLECTION

Algorithms · Dynamic Programming

19 questions, newest first

GATE CSE has asked 19 questions on Dynamic Programming (Algorithms) from 1998 to 2026, in 14 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 0.4 marks per 100-mark paper on average, against 0.8 since 2003. Since 2014 the questions have been 4 NAT, 3 MCQ and 1 MSQ. 3 groups of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
2 marks · MCQ
Report issue

Two valid dynamic-programming orders

Dynamic Programming

Question 39, GATE 2026: T[0][k]=T[k][0]=1 for 0≤k≤n; for 1≤i,j≤n use T[i][j]=2T[i−1][j]+3T[i][j−1]. All cells initially equal 1. B1 loops i=1…n then j=1…n and updates each interior cell. B2 loops s=2…2n, then all i,j=1…n, updating only when i+j=s. Which is correct? A both; B only B1; C only B2; D neither.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Givens and goal

T[0][k]=T[k][0]=1 for 0≤k≤n; for 1≤i,j≤n use T[i][j]=2T[i−1][j]+3T[i][j−1]. All cells initially equal 1. B1 loops i=1…n then j=1…n and updates each interior cell. B2 loops s=2…2n, then all i,j=1…n, updating only when i+j=s. Which is correct? A both; B only B1; C only B2; D neither.

Approach

Check whether the dependencies are ready before each update.

Step-by-step solution

1. Each interior cell depends only on its upper neighbor (i−1,j) and left neighbor (i,j−1). The coefficients 2 and 3 do not affect the ordering requirement.
2. In B1, row i−1 has already been completed when row i begins. Within row i, j increases, so the left neighbor has already been computed. Boundary neighbors retain their initialized correct values.
3. In B2, both dependencies have coordinate sum i+j−1=s−1. They were processed in the previous diagonal layer, unless they lie on a preinitialized boundary. Every interior cell has a unique sum between 2 and 2n and is updated exactly once.
4. For a small check, T[1][1]=2+3=5; T[1][2]=2×1+3×5=17; T[2][1]=2×5+3×1=13; T[2][2]=2×17+3×13=73. Either order produces these values.
5. Both are correct, A. B1 performs Θ(n²) work, whereas the stated B2 scans n² pairs for Θ(n) values of s and takes Θ(n³). Correctness does not require equal efficiency.

Original paper, page 26 · Answer key

1 mark · NAT
Report issue

Minimum replacements via a longest nondecreasing subsequence

Dynamic Programming

Question 35, GATE 2024: The distance of an integer array is the least number of entries replaced by arbitrary integers to make it nondecreasing. Find the distance of [2,5,3,1,4,2,6].
Tap to enlarge
Answer & solution

Official answer: 3

Step through it (9 steps)

Approach: Any entries kept in place must already form a nondecreasing subsequence; combine that lower bound with an explicit repair.

1. Derivation. Any unchanged elements must form a nondecreasing subsequence. Longest nondecreasing subsequence lengths ending at the seven positions are 1, 2, 2, 1, 3, 2, 4, so at most 4 elements can remain unchanged and at least 7−4=3 replacements are needed. Keep the subsequence 2, 3, 4, 6 at positions 1, 3, 5, 7; replace positions 2, 4, 6 by 2, 3, 4 respectively to obtain[2, 2, 3, 3, 4, 4, 6]. Thus3 is achievable and minimal.

2. Explanation and checks. For each position i define L[i]=1+max L[j] over j<i with A[j]≤A[i], or 1 if there is no such j. This yields [1,2,2,1,3,2,4], with maximum 4. Therefore keeping five entries is impossible. The displayed repair keeps four original entries and changes exactly three, establishing the matching upper bound. It is a replacement problem, not a sorting-by-swaps problem, and equality is allowed in the final array.

Original paper, page 23 · Answer key

2 marks · MSQ
Report issue

Dynamic Programming

Question 40, GATE 2021: Let R_n be the maximum revenue from cutting a rod of integer length n into one or more integer-length pieces. Prices for lengths 1,...,7 are 1,5,8,9,10,17,18. Select all true statements: A R7=18; B R7=19; C R7 is achieved by three different solutions; D no three-piece solution achieves R7. Different piece orders are not different cutting solutions.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A; C

With R0=0 and Rn=max1≤i≤n(p[i]+Rn−i), the values R1,…, R7 are 1, 5, 8, 10, 13, 17, 18. Revenue18 is achieved by exactly the three unordered partitions 7; 6+1; 3+2+2. The last uses three pieces, so D is false, and 19 is not attainable. Hence A, C. Different orders of the same piece lengths are not counted as distinct cutting solutions.

Dynamic-programming pseudocode: R[0]=0; for length=1..7: R[length]=max(price[i]+R[length−i] for i=1..length). At length 7 the candidates for first piece sizes 1..7 are 18,18,18,17,15,18,18. Backtracking optimal candidates and sorting piece lengths gives {7},{1,6},{2,2,3}; different first-piece choices can lead to the same sorted partition, so count each only once. The recurrence is exhaustive because every nonempty cutting solution has some first piece and an optimally solved remainder.

Original paper, page 34 · Answer key

1 mark · NAT
Report issue

Maximum contiguous-subarray sum

Dynamic Programming

Question 25, GATE 2019: For A=[−5,−10,6,3,−1,−2,13,4,−9,−1,4,12,−3,0], find the maximum S(i,j)=sum of A[k] for k=i through j, with 0≤i≤j<14. The chosen elements must form a contiguous segment.
Tap to enlarge
Answer & solution

Official answer: 29

Method: use Kadane's dynamic program. Let E[j] be the largest sum of any nonempty segment ending exactly at j. Such a segment either starts at j or extends the best segment ending at j−1.

1. The recurrence is E[0]=A[0]=−5 and E[j]=max(A[j],E[j−1]+A[j]). It is exhaustive because every segment ending at j has one of those two forms.
2. At indices 0 and 1, E is −5 then max(−10,−15)=−10. At index 2, starting afresh with 6 beats extending the negative prefix, so E[2]=6 and the candidate segment starts at index 2.
3. Continue through indices 3 to 7: E values are 9,8,6,19,23. Although −1 and −2 reduce the running sum, discarding the accumulated positive prefix would be worse.
4. For indices 8 to 13 the values are 14,13,17,29,26,26. The maximum across all E values is 29, achieved at j=11.
5. Recover the segment from i=2 through j=11: 6+3−1−2+13+4−9−1+4+12=29. The negative terms inside it must remain because the segment is contiguous.
6. Since every segment has some ending index j and E[j] is optimal for that ending index, taking the largest E[j] proves that no omitted segment has a greater sum.

Result: 29. The prompt permits divide and conquer but does not require it; this linear-time recurrence gives the same optimum and a direct correctness argument.

Original paper, page 9 · Answer key

2 marks · MCQ
Report issue

Optimal matrix-chain multiplication

Dynamic Programming

Question 31, GATE 2018: Matrices F1…F5 have dimensions 2×25,25×3,3×16,16×1,1×1000. Multiplying p×q by q×r costs pqr scalar operations. Which adjacent original pairs are directly multiplied in an optimal parenthesization? A F1F2 and F3F4; B F2F3; C F3F4; D F1F2 and F4F5.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (12 steps)

Method

The dynamic-programming state M[i,j] is the minimum scalar cost of multiplying the consecutive subchain; a split k adds the costs of its two subchains and their final product. This systematically tests all parenthesizations without a local greedy assumption. In the winning chain, F3F4 first produces 3×1 at cost 48; F2 times that gives 25×1 at cost 75; F1 times that gives 2×1 at cost 50; multiplying F5 costs 2000. Only the first operation multiplies two original matrices directly.

Solution

Use matrix-chain DP: M[i, j]=mink(M[i, k]+M[k+1, j]+d[i−1]d[k]d[j]). Dimensions are 2, 25, 3, 16, 1, 1000. Pair costs are 150, 1200, 48, 16000; three-matrix optimal costs 246, 123, 3048; four-matrix costs 173, 25123. Splitting the full chain after F1, F2, F3, F4 costs 75123, 9198, 48246, 2173 respectively. The unique optimum is((F1(F2(F3F4)))F5), costing 48+75+50+2000=2173. Its only directly multiplied original pair is F3F4, C.

Original paper, page 13 · Answer key

1 mark · MCQ
Report issue

Dynamic Programming

Question 14, GATE 2016: Which paradigm underlies Floyd–Warshall all-pairs shortest paths? A greedy; B divide-and-conquer; C dynamic programming; D none of these.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Floyd–Warshall maintains shortest distances whose allowed intermediate vertices come from the first k vertices, updating dk(i, j)=min(dk−1(i, j), dk−1(i, k)+dk−1(k, j)). Reusing these subproblems is dynamic programming, C.

Define Dk(i,j) as the best i-to-j path using only vertices 1,…,k internally. Such a path either avoids k or decomposes through k into two earlier subproblems. Initialize D0 with edge weights, zero diagonals and infinity for absent edges. Iterating k,i,j uses Θ(V³) time and can reuse one distance matrix.

Original paper, page 29 · Answer key

2 marks · NAT
Report issue

Dynamic Programming

Question 38, GATE 2016: Matrices A1,A2,A3,A4 have dimensions 10×5,5×20,20×10,10×5. Find the minimum number of scalar multiplications using ordinary matrix multiplication to compute their product.
Tap to enlarge
Answer & solution

Official answer: 1500.0 : 1500.0

Our answer: 1500

Step through it (8 steps)

Use A1((A2A3)A4): A2A3 costs 5·20·10=1000 and yields 5×10; multiplying A4 costs 5·10·5=250 and yields 5×5; multiplying A1 costs 10·5·5=250. Total 1500. The five full parenthesizations cost 1750, 1500, 3000, 2000, 3500, so 1500 is minimal.

Matrix-chain DP uses M(i,j)=min over k of M(i,k)+M(k+1,j)+di−1dk dj, with M(i,i)=0. For d=(10,5,20,10,5), two-matrix costs are 1000,1000,1000; three-matrix optima are M(1,3)=1500 and M(2,4)=1250. Splitting the full chain after A1 then costs 1250+250=1500.

Original paper, page 35 · Answer key

2 marks · NAT
Report issue

Dynamic Programming

Question 37, GATE 2014: Move from 0 to 100 on the number line. One step either moves from k to k+1 or takes a supplied shortcut (i,j), i<j, directly from i to j. At most one shortcut involves any number; in particular 9 has a shortcut to 15. T(k) is the minimum steps from k to 100. If T(9)=1+min(T(y),T(z)), find yz.
Tap to enlarge
Answer & solution

Official answer: 150

Step 1: Condition on the first move from 9. The ordinary unit move reaches 10; the available shortcut reaches 15. Each costs one step. Step 2: Once the first move is made, the optimal remaining cost is T(10) or T(15), so optimal substructure yields T(9)=1+min(T(10),T(15)). Step 3: The order of y and z is irrelevant: their product is 10×15=150. No knowledge of the remaining shortcuts is needed to identify these two immediate successor states.

Original paper, page 61 · Answer key

1 mark · MCQ
Report issue

Dynamic program for increasing contiguous runs

Dynamic Programming

Question 25, GATE 2011: An array algorithm initializes L[n-1]=1 and for 0≤i≤n-2 defines L[i]=1+L[i+1] when A[i]<A[i+1], otherwise L[i]=1. It returns max(L[0],...,L[n-1]). The source calls this the longest monotonically increasing sequence. Which statement is TRUE?

(A) It uses dynamic programming
(B) It has linear complexity and uses branch and bound
(C) It has nonlinear polynomial complexity and uses branch and bound
(D) It uses divide and conquer
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Compute the displayed Li from right to left, reusing the already-computed Li+1. This is a dynamic program with linear time and the maximum Li as output, so A. Its recurrence computes strictly increasing contiguous runs; it is not the general longest increasing subsequence algorithm when skipped elements are permitted. A suitable evaluation order is needed even though the source writes the index range without an order.

For the recurrence to run, process i=n-2,n-3,...,0. If adjacent entries increase, the run beginning at i is the current element followed by the already-solved run at i+1; otherwise it ends immediately. Each table entry takes constant work, and the final maximum takes linear work. For A=[1,3,2,4], every increasing contiguous run has length 2, although the noncontiguous subsequence [1,2,4] has length 3. This illustrates the important limitation of the displayed recurrence.

Original paper, page 6 · Answer key

2 marks · MCQ
Report issue

Matrix-chain multiplication optimum

Dynamic Programming

Question 38, GATE 2011: Four matrices M1,M2,M3,M4 have dimensions 10×100,100×20,20×5,5×80. Multiplication of an a×b matrix by a b×c matrix costs abc scalar multiplications. What is the minimum total for their ordered product over all parenthesizations?

(A) 248000
(B) 44000
(C) 19000
(D) 25000
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (8 steps)

For dimensions 10, 100, 20, 5, 80, the five full parenthesizations have costs 25000 for(((AB)C)D), 19000 for((A(BC))D), 44000 for((AB)(CD)), 130000 for(A((BC)D)) and 248000 for(A(B(CD))). The minimum is 19000, attained by BC costing 100×20×5=10000, then A(BC) costing 10×100×5=5000, then the final product costing 10×5×80=4000. Thus C.

Label the matrices A,B,C,D. Dimensions of intermediate results matter: BC is 100×5, A(BC) is 10×5, and the final product is 10×80. Multiplying the dimensions of each operation yields the stated 10000+5000+4000 optimum. Checking all five full binary parenthesizations proves that this is a global minimum, not merely a good greedy choice. For example, doing AB first already costs 20000 before the remaining work, exceeding the optimum by itself.

Original paper, page 10 · Answer key

2 marks · MCQ
Report issue

Maximum weighted subsequence recurrence

Dynamic Programming

Question 34, GATE 2010: The weight of a real sequence a₀,…,aₙ₋₁ is a₀+a₁/2+⋯+aₙ₋₁/2^(n−1). A subsequence deletes elements without changing the order. X is the maximum subsequence weight of a₀,…,aₙ₋₁ and Y is that of a₁,…,aₙ₋₁. What is X?
Options: (A) max(Y,a₀+Y); (B) max(Y,a₀+Y/2); (C) max(Y,a₀+2Y); (D) a₀+Y/2.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Split subsequences according to whether they include a₀. If not, their optimum weight is Y, the optimum on the suffix. If they do, a₀ contributes with weight 1 and each selected suffix element shifts one position, halving its contribution; the best such weight is a₀+Y/2. Thus X=max(Y,a₀+Y/2), B. The usual subsequence convention permits the empty subsequence, ensuring this also works with negative inputs.

The split is exhaustive and disjoint: every candidate either omits a₀ or contains it. Including a₀ shifts every chosen suffix element one weight position to the right, multiplying the entire suffix weight by 1/2; its internal order and relative weights are unchanged. Since 1/2 is positive, the suffix maximizing its own weight also maximizes the scaled weight. The outer maximum is necessary because including a negative a₀ can be harmful.

Original paper, page 8

2 marks · MCQ
Report issue

Longest common subsequence recurrence

Dynamic Programming

Question 53, GATE 2009: Let l(i, j) be LCS length of prefixes of lengths i, j of zero-indexed X, Y. Boundary l=0 if either prefix empty; expr1 applies if last symbols match, expr2 otherwise. Which proposal is correct? A expr1=l(i−1, j)+1; B expr1=l(i, j−1); C expr2=max(l(i−1, j), l(i, j−1)); D expr2=max(l(i−1, j−1), l(i, j)).
Question 53, GATE 2009: Let l(i, j) be LCS length of prefixes of lengths i, j of zero-indexed X, Y. Boundary l=0 if either prefix empty; expr1 applies if last symbols match, expr2 otherwise. Which proposal is correct? A expr1=l(i−1, j)+1; B expr1=l(i, j−1); C expr2=max(l(i−1, j), l(i, j−1)); D expr2=max(l(i−1, j−1), l(i, j)).
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Let l(i, j) be the LCS length of the first i elements of X and first j elements of Y. If either prefix is empty, l(i, j)=0. When X[i−1]=Y[j−1], the matching final elements extend an optimal LCS of both shortened prefixes, so expr1=l(i−1, j−1)+1. If they differ, an LCS omits at least one of the two final elements, yielding expr2=max(l(i−1, j), l(i, j−1)). Only option C gives a correct proposed expression. A omits shortening Y in the matching case, B omits both the match increment and shortening X, and D is circular.

If the last symbols match, use that matched pair and extend the best solution for both shorter prefixes: l(i−1, j−1)+1. If they differ, a common subsequence must omit at least one of them, so take the larger of the two one-prefix-shortened values. Only C states a valid supplied formula. Option D references l(i, j) on its own right side and cannot define a bottom-up recurrence.

Original paper, page 12

2 marks · MCQ
Report issue

Legal LCS dynamic-programming fill orders

Dynamic Programming

Question 54, GATE 2009: Store the LCS recurrence in L[m+1, n+1]. Which is true? A every cell must first be zero; B increasing row-major or column-major computation works; C neither works; D L[p, q] must precede L[r, s] whenever p<r OR q<s.
Question 54, GATE 2009: Store the LCS recurrence in L[m+1, n+1]. Which is true? A every cell must first be zero; B increasing row-major or column-major computation works; C neither works; D L[p, q] must precede L[r, s] whenever p<r OR q<s.
Question 54, GATE 2009: Store the LCS recurrence in L[m+1, n+1]. Which is true? A every cell must first be zero; B increasing row-major or column-major computation works; C neither works; D L[p, q] must precede L[r, s] whenever p<r OR q<s.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Initialize only the empty-prefix boundary L[0, j]=L[i, 0]=0. Every other L[i, j] depends on L[i−1, j−1] in the matching case, or on L[i−1, j] and L[i, j−1] in the nonmatching case. Increasing-index row-major order computes all predecessors first; increasing-index column-major order also does so. Therefore B. Initializing every cell to zero is not necessary (A), and C contradicts these valid orders. D overstates the dependency: p<r alone does not require an arbitrarily far-right cell L[p, q] before L[r, s]; its OR condition can even demand opposite orders for incomparable cells such as (1, 2) and (2, 1).

The dependency arrows point left, up or diagonally up-left. Both increasing row order and increasing column order place all those predecessor cells before the current cell. Only row 0 and column 0 require initialization; every interior cell can be assigned when reached. The proposed OR ordering in D is too strong: cells(1, 2) and(2, 1) would each be required before the other. Therefore B.

Original paper, page 12

2 marks · MCQ
Report issue

Subset-sum dynamic-programming recurrence

Dynamic Programming

Question 80, GATE 2008: Given positive integers S={a₁,…,aₙ} and target W>0, a subset-sum dynamic program uses Boolean X with n rows and W+1 columns. X[i,j] is true iff some subset of {a₁,…,aᵢ} sums to j, for 1≤i≤n and 0≤j≤W. Which recurrence is valid for 2≤i≤n and aᵢ≤j≤W?

(A) X[i,j]=X[i−1,j]∨X[i,j−aᵢ]
(B) X[i,j]=X[i−1,j]∨X[i−1,j−aᵢ]
(C) X[i,j]=X[i−1,j]∧X[i,j−aᵢ]
(D) X[i,j]=X[i−1,j]∧X[i−1,j−aᵢ]
Question 80, GATE 2008: Given positive integers S={a₁,…,aₙ} and target W>0, a subset-sum dynamic program uses Boolean X with n rows and W+1 columns. X[i,j] is true iff some subset of {a₁,…,aᵢ} sums to j, for 1≤i≤n and 0≤j≤W. Which recurrence is valid for 2≤i≤n and aᵢ≤j≤W?

(A) X[i,j]=X[i−1,j]∨X[i,j−aᵢ]
(B) X[i,j]=X[i−1,j]∨X[i−1,j−aᵢ]
(C) X[i,j]=X[i−1,j]∧X[i,j−aᵢ]
(D) X[i,j]=X[i−1,j]∧X[i−1,j−aᵢ]
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Consider whether the chosen subset contains aᵢ. If not, the first i−1 elements alone must sum to j, represented by X[i−1,j].
2. If aᵢ is included, remove it once; the remaining subset of the first i−1 elements must sum to j−aᵢ, represented by X[i−1,j−aᵢ].
3. Either alternative suffices, so combine with OR, giving B. Using row i in the second term allows repeated copies of aᵢ; AND incorrectly requires both choices.

Original paper, page 17

2 marks · MCQ
Report issue

Subset-sum answer table cell

Dynamic Programming

Question 81, GATE 2008: Given positive integers S={a₁,…,aₙ} and target W>0, a subset-sum dynamic program uses Boolean X with n rows and W+1 columns. X[i,j] is true iff some subset of {a₁,…,aᵢ} sums to j, for 1≤i≤n and 0≤j≤W. Which entry, if TRUE, implies there is a subset summing to W? (This preserves the printed one-way wording.)

(A) X[1,W]
(B) X[n,0]
(C) X[n,W]
(D) X[n−1,n]
Question 81, GATE 2008: Given positive integers S={a₁,…,aₙ} and target W>0, a subset-sum dynamic program uses Boolean X with n rows and W+1 columns. X[i,j] is true iff some subset of {a₁,…,aᵢ} sums to j, for 1≤i≤n and 0≤j≤W. Which entry, if TRUE, implies there is a subset summing to W? (This preserves the printed one-way wording.)

(A) X[1,W]
(B) X[n,0]
(C) X[n,W]
(D) X[n−1,n]
Question 81, GATE 2008: Given positive integers S={a₁,…,aₙ} and target W>0, a subset-sum dynamic program uses Boolean X with n rows and W+1 columns. X[i,j] is true iff some subset of {a₁,…,aᵢ} sums to j, for 1≤i≤n and 0≤j≤W. Which entry, if TRUE, implies there is a subset summing to W? (This preserves the printed one-way wording.)

(A) X[1,W]
(B) X[n,0]
(C) X[n,W]
(D) X[n−1,n]
Tap to enlarge
Your answer
Answer & solution

Answer: C intended; A also satisfies the literal implication (no official key was published)

1. By the definition of X, X[n,W] is true if and only if a subset of all n inputs sums to W. Therefore C is the terminal decision cell intended by the algorithm.
2. However, the printed wording asks only which TRUE entry implies the existence of a subset summing to W. X[1,W] being true also implies that fact, since {a1} is contained in the full set.
3. B is always true via the empty subset and D concerns sum n rather than W. Thus A and C both satisfy the literal one-way implication; C alone is necessary and sufficient for the full problem.

Original paper, page 17

2 marks · MCQ
Report issue

Memoized recurrence storage

Dynamic Programming

Question 81b, GATE 2005: double foo(int n){int i;double sum;if(n==0)return 1.0;sum=0.0;for(i=0;i<n;i++)sum+=foo(i);return sum;} Printed 81(b): memoize foo(i), 0≤i<n, as computed. Auxiliary space? A O(1); B O(n); C O(n²); D O(n!).
Question 81b, GATE 2005: double foo(int n){int i;double sum;if(n==0)return 1.0;sum=0.0;for(i=0;i<n;i++)sum+=foo(i);return sum;} Printed 81(b): memoize foo(i), 0≤i<n, as computed. Auxiliary space? A O(1); B O(n); C O(n²); D O(n!).
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Caching foo(i) for 0≤i<n requires n scalar values, hence Θ(n) space. Any recursive call stack is also at most O(n), so the total remains Θ(n), option B. Memoization reduces recomputation but does not require storing all call-tree nodes. This counts machine words, as in the question’s double-valued implementation.

Memoization allocates one result per argument value, a linear-size table, rather than one result per recursive-call occurrence. A recursive implementation can still have a linear stack, but adding two linear requirements remains linear. The table itself gives a linear lower bound in the stated storage scheme. Count constant-size machine words as specified by the double implementation; arbitrary-precision value bit lengths would be a different model.

Original paper, page 11

Descriptive
Report issue

Memoize Fibonacci recursion

Dynamic Programming

Question 16(a), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. Fill the three boxes.
Question 16(a), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. Fill the three boxes.
Tap to enlarge
Answer & solution

Answer: (1) f[n]!=0; (2) f[n]; (3) f[n]=t; (no official key was published)

The completed function is:
fib(n) {
  if (n > M) error();
  if (n == 0) return 1;
  if (n == 1) return 1;
  if (f[n] != 0) return f[n];
  t = fib(n-1) + fib(n-2);
  f[n] = t;
  return t;
}

Use a local t in each recursive activation. Since both base cases equal 1, every valid Fibonacci result is positive. Thus zero safely means “not computed” under the stated exact-arithmetic model. On a cache miss, recursively obtain the two predecessors, store their sum before returning, and reuse it whenever n is requested again. For example fib(4) obtains fib(3)=3, then reads the cached fib(2)=2, producing 5. The base cases need not be stored because they already take constant time. With overflowing machine arithmetic, zero might cease to be a valid sentinel; practical implementations can use an independent computed flag or arbitrary-precision values.

Original paper, page 9

Descriptive
Report issue

Bound memoized Fibonacci work

Dynamic Programming

Question 16(b), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. With memoization filled correctly, find the running time of the first fib(n) computation.
Question 16(b), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. With memoization filled correctly, find the running time of the first fib(n) computation.
Question 16(b), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. With memoization filled correctly, find the running time of the first fib(n) computation.
Tap to enlarge
Answer & solution

Answer: Θ(n) time in the unit-cost arithmetic model; Θ(n) recursion depth and used cache cells. (no official key was published)

For each k from 2 through n there is at most one cache miss. That miss performs a constant number of comparisons, two recursive calls, one addition and one store. All later calls on the same k return from the cache in constant time. The subproblem dependency graph has n+1 possible arguments and two outgoing calls per non-base argument, so the total number of calls and primitive operations is O(n), not exponential. A first computation must actually compute each of fib(2),...,fib(n), giving Ω(n) work; therefore the tight bound is Θ(n). The descent n,n−1,...,1 can occupy Θ(n) stack frames. Initializing the provided whole array costs Θ(M) separately, but the stem says it is already initialized. If bit complexity is counted, Fibonacci numbers have Θ(n) bits, and the n additions have increasing cost; the conventional linear answer assumes constant-time arithmetic.

Original paper, page 9

1 mark · MCQ
Report issue

All-pairs shortest paths

Dynamic Programming

Question 1.21, GATE 1998: Which technique underlies the standard all-pairs shortest-path algorithm: dynamic programming, backtracking, greedy, divide-and-conquer?
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Floyd–Warshall defines Dk (i, j) as the best path using only the first k vertices as intermediates. It either avoids k or passes through it, yielding Dk (i, j)=min (Dk−1(i, j), Dk−1(i, k)+Dk−1(k, j)). Reusing these overlapping subproblem values is dynamic programming, A. The answer refers to this standard all-pairs algorithm; other algorithms can solve restricted graph classes, so the task name alone is not a proof that every possible implementation uses the same paradigm.

Original paper, page 2