GATE / CS ARCHIVE

SUBJECT COLLECTION

Algorithms · Correctness, Invariants & Design

14 questions, newest first

GATE CSE has asked 14 questions on Correctness, Invariants & Design (Algorithms) from 1991 to 2026, in 12 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 0.5 marks per 100-mark paper on average, against 0.3 since 2003. Since 2014 the questions have been 3 MCQ and 1 NAT. 1 group of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
2 marks · MCQ
Report issue

Checking increasing adjacent differences

Correctness, Invariants & Design

Question 38, GATE 2026: For integer A[1…n], determine whether for every i>j in {1,…,n−1}, A[i+1]−A[i] > A[j+1]−A[j]. Choose optimal worst-case time: A Θ(n); B Θ(log n); C Θ(n log n); D Θ(n²).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Givens and goal

For integer A[1…n], determine whether for every i>j in {1,…,n−1}, A[i+1]−A[i] > A[j+1]−A[j]. Choose optimal worst-case time: A Θ(n); B Θ(log n); C Θ(n log n); D Θ(n²).

Approach

Reduce all pairwise comparisons to adjacent comparisons using transitivity.

Step-by-step solution

1. Define d_i=A[i+1]−A[i]. The condition says each later difference is larger than every earlier one. This is equivalent to d_1<d_2<…<d_(n−1).
2. The forward implication includes all adjacent pairs. Conversely, if adjacent inequalities hold, chaining d_j<d_(j+1)<…<d_i proves the required inequality for every i>j.
3. Algorithm: if n≤2 return true; set previous=A[2]−A[1]; for i=2,…,n−1 set current=A[i+1]−A[i]; if current≤previous return false; otherwise set previous=current. If the loop ends return true. Only O(1) extra storage is needed.
4. The loop uses O(n) time. For a lower bound, consider a valid array such as A[i]=i², whose differences are strictly increasing. If any position is unread, an adversary can change that entry sufficiently to violate a neighboring comparison while leaving all inspected values unchanged. Thus worst-case inspection requires Ω(n) entries for n≥3.
5. The optimal bound is Θ(n), A. Use sufficiently wide arithmetic so subtraction does not overflow; the proof is in the mathematical-integer model.

Original paper, page 25 · Answer key

2 marks · MCQ
Report issue

Maintain the one-run and two-value suffix invariants

Correctness, Invariants & Design

Question 42, GATE 2024: For positive X[0..n−1], initialize first=second=len1=len2=maxlen=0. For each v=X[i]: if v==first increment both len1,len2; else if v==second increment len2, set len1=P, second=first; else set len2=Q, len1=1, second=first. Update maxlen=max(maxlen,len2), then first=v. len1 is the equal-value suffix length; len2 is the suffix length with at most two distinct values. Choose P,Q: A len1+1,len2+1; B 1,len1+1; C 1,len2+1; D len2+1,len1+1.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Approach: Interpret the saved values before the current iteration updates them.

1. Derivation. first is the previous element and len1 is its final equal-value run length. If the next item equals second but differs from first, the final equal run starts anew, so P=1, while the valid two-value suffix extends by one. If a third distinct value arrives, only the previous final run can accompany it; therefore the new two-value suffix has length len1+1, giving Q=len1+1. The assignments update second to the old first. Thus B; positive input values ensure initial zero sentinels are not actual array values.

2. Explanation and checks. For the prefix [1,2,2], len1=2 and len2=3. If the next value is 1, it is the other known value: the two-value suffix grows to 4, but the same-value suffix has length 1. If instead the next value is 3, keeping all three old elements would create three distinct values; only [2,2,3] is legal, of length old len1+1=3. Updating first last preserves the old run value while second is assigned.

Original paper, page 29 · Answer key

2 marks · MCQ
Report issue

Correctness, Invariants & Design

Question 35, GATE 2016: Code for positive X,Y: int exp(int X,int Y){int res=1,a=X,b=Y; while(b!=0){if(b%2==0){a=a*a;b=b/2;}else{res=res*a;b=b-1;}}return res;}. Which invariant holds before every iteration? A X^Y=a^b; B (res*a)^Y=(res*X)^b; C X^Y=res*a^b; D X^Y=(res*a)^b.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C under no-overflow arithmetic

The invariant is X^Y=res·a^b, C. Initially res=1, a=X, b=Y. An even step replaces(a, b) by(a², b/2), preserving a^b. An odd step multiplies res by a and decreases b by 1, preserving the product. At termination b=0, res=X^Y. This mathematical proof assumes intermediates fit the C int type; arbitrary positive inputs can overflow signed int and then lack defined C behavior.

For example X=2,Y=3 gives states (res,a,b)=(1,2,3),(2,2,2),(2,4,1),(8,4,0). The invariant product is 8 at each state. Option A fails once a factor moves into res; option D incorrectly raises res to b. Initialization, preservation and termination are three distinct obligations in a loop-invariant proof.

Original paper, page 34 · Answer key

2 marks · NAT
Report issue

Correctness, Invariants & Design

Question 63, GATE 2015: DOSOMETHING(c,a,n) receives a bit array c[0..k−1] and positive integers a,n. It sets z=1; then for i=0,...,k−1 sets z=z² mod n, and, if c[i]=1, sets z=(z×a) mod n; finally it returns z. For k=4, c=(1,0,1,1), a=2, n=8, what is returned?
Tap to enlarge
Answer & solution

Official answer: 0

1. Iteration details: bit 1 gives 1²·2 mod 8=2; bit 0 gives 2² mod 8=4; bit 1 gives (4² mod 8)·2 mod 8=0; the last bit 1 keeps the value 0. Each iteration squares before the optional multiplication.

2. The loop processes the binary exponent 1011 from most significant bit to least. The successive z values modulo 8 are 2, 4, 0, 0: square and multiply by 2 when the current bit is 1. Equivalently it computes 211 mod8=0.

Original paper, page 78 · Answer key

1 mark · MCQ
Report issue

Array leaders and traversal direction

Correctness, Invariants & Design

Question 17, GATE 2006: An array element is a leader if it exceeds every element to its right. Which description gives the best algorithm for finding all leaders? No auxiliary-space restriction is stated, which affects whether the options are exclusive.
Options:
(A) Linear time with a left-to-right pass
(B) Linear time with a right-to-left pass
(C) Divide and conquer in Θ(n log n)
(D) Θ(n²) time
Tap to enlarge
Your answer
Answer & solution

Answer: B with constant extra space; A also possible with a stack (no official key was published)

1. Scanning right to left while retaining the largest value seen reports exactly the elements strictly larger than every element to their right. This is Θ(n) time and O(1) extra working space, yielding the usual B.

2. However A is also achievable in linear time if extra storage is allowed: scan left to right, keep candidate leaders in a decreasing stack, and pop every prior candidate≤the new value before pushing it. Each entry is pushed/popped at most once; the final stack contains the leaders.

3. Since the prompt does not require constant space, traversal direction alone does not make B uniquely correct.

4. Teaching check: Right-to-left scanning initializes the current maximum with the rightmost element and reports a new element only when it is strictly greater. Equal values do not become leaders if an equal value occurs later. A left-to-right monotone stack is a separate linear-time possibility, explaining the nonunique direction-only options.

Original paper, page 2

2 marks · MCQ
Report issue

Arithmetic-mean square-root iteration

Correctness, Invariants & Design

Question 42, GATE 2004: For real arithmetic, m>1 and ε>0, what does this algorithm approximate?
x=m; y=1;
while(x-y>ε) { x=(x+y)/2; y=m/x; }
print(x);
Options:
(A) log m
(B) m²
(C) m^(1/2)
(D) m^(1/3)
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. In real arithmetic xy=m initially and after each iteration. Thus x is an upper bound and y=m/x a lower bound for sqrt(m).

2. Updating x to (x+m/x)/2 preserves x≥sqrt(m) and decreases it unless equality holds; resetting y preserves the invariant. The limits agree at sqrt(m).

3. At termination y≤sqrt(m)≤x and x−y≤epsilon, giving absolute error at most epsilon. This is an algorithm question about iteration, not a request to solve an excluded calculus topic; integer division would invalidate the real-arithmetic interpretation.

4. Teaching check: After the update, x is the arithmetic mean of a pair whose product is m, so x≥sqrt(m) by AM–GM. Setting y=m/x gives y≤sqrt(m). Their shrinking gap supplies a direct error bound, not merely a guess based on numerical similarity.

Original paper, page 6

2 marks · MCQ
Report issue

Array rotation by three reversals

Correctness, Invariants & Design

Question 2.15, GATE 2000: For array s[1…n] and 1≤k≤n, execute reverse(s,1,k),reverse(s,k+1,n),reverse(s,1,n). Does this rotate left by k,leave unchanged,reverse everything,or none?
Question 2.15, GATE 2000: For array s[1…n] and 1≤k≤n, execute reverse(s,1,k),reverse(s,k+1,n),reverse(s,1,n). Does this rotate left by k,leave unchanged,reverse everything,or none?
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step 1: Split the original array into consecutive blocks A=s[1…k] and B=s[k+1…n], so it is AB. The first two operations produce AR BR.

Step 2: Reversing the whole concatenation reverses block order and each block: (AR BR)R=BA. This moves the first k entries to the end while preserving order within each block.

Thus A, a left rotation by k. For k=n, the second range is empty and must be treated as a no-op; the full rotation leaves the array unchanged.

Original paper, page 5

Descriptive
Report issue

Complete line intersection test

Correctness, Invariants & Design

Question 14(b), GATE 2000: Let m,n be positive integers and let the line be y=(n/m)x. Define A=mq−np for endpoint (p,q), and B=ms−nr for endpoint (r,s). Complete clash: initialize false; line4 tests A [box] 0; line5 tests B [box] 0; line6 tests A [box] 0 and B [box] 0; line7 tests A [box] 0 and B [box] 0. Each successful test sets clash=true.
Question 14(b), GATE 2000: Let m,n be positive integers and let the line be y=(n/m)x. Define A=mq−np for endpoint (p,q), and B=ms−nr for endpoint (r,s). Complete clash: initialize false; line4 tests A [box] 0; line5 tests B [box] 0; line6 tests A [box] 0 and B [box] 0; line7 tests A [box] 0 and B [box] 0. Each successful test sets clash=true.
Tap to enlarge
Answer & solution

Answer: Line4 =; line5 =; line6 < and >; line7 > and < (last two cases may be exchanged). (no official key was published)

A segment intersects the infinite line if either endpoint lies on it, or if its endpoints lie on opposite sides. The completed Pascal-style code is:

function clash(m,n,p,q,r,s: integer): Boolean;
begin
  clash := false;
  if (m*q-n*p) = 0 then clash := true;        {line 4}
  if (m*s-n*r) = 0 then clash := true;        {line 5}
  if (m*q-n*p) < 0 and (m*s-n*r) > 0 then clash := true; {6}
  if (m*q-n*p) > 0 and (m*s-n*r) < 0 then clash := true; {7}
end;

For a point interpolated along the segment with parameter t in [0,1], the signed expression is (1−t)A+tB. If A and B have opposite signs, this linear continuous function has a zero in the interval. If both have the same nonzero sign, every convex combination has that sign and there is no intersection. Endpoint equality also handles a zero-length segment lying on the line and a whole segment coincident with it. Avoid multiplying A*B merely to test the signs: that introduces extra overflow risk. As mathematical pseudocode, the original arithmetic assumes exact integer results.

Original paper, page 8

5 marks · Descriptive
Report issue

Complete a shortest-window algorithm

Correctness, Invariants & Design

Question 17, GATE 1997: An array A[1..n], n≥1, contains positive integers, and M>0. Complete the boxes in this program so it prints the shortest nonempty contiguous-subarray length having sum at least M, or n+1 if none exists. The program uses one-based array indexing:
1 begin
2   i:=1; j:=1;
3   sum:=[B3];
4   min:=n; finish:=false;
5   while not finish do
6     if [B6] then
7       if j=n then finish:=true
8       else
9         begin
10          j:=j+1;
11          sum:=[B11]
12        end
13    else
14      begin
15        if (j-i)<min then min:=j-i;
16        sum:=sum-A[i];
17        i:=i+1
18      end;
19  writeln(min+1)
20 end
Question 17, GATE 1997: An array A[1..n], n≥1, contains positive integers, and M>0. Complete the boxes in this program so it prints the shortest nonempty contiguous-subarray length having sum at least M, or n+1 if none exists. The program uses one-based array indexing:
1 begin
2   i:=1; j:=1;
3   sum:=[B3];
4   min:=n; finish:=false;
5   while not finish do
6     if [B6] then
7       if j=n then finish:=true
8       else
9         begin
10          j:=j+1;
11          sum:=[B11]
12        end
13    else
14      begin
15        if (j-i)<min then min:=j-i;
16        sum:=sum-A[i];
17        i:=i+1
18      end;
19  writeln(min+1)
20 end
Tap to enlarge
Answer & solution

Answer: B3=A[1]; B6=sum<M; B11=sum+A[j]. (no official key was published)

Fill line 3 with A[1], line 6 with sum<M, and line 11 with sum+A[j]. The invariant is that sum equals A[i]+…+A[j], with value zero if the current window is empty (i=j+1).

Initially i=j=1, so sum must be A[1]. If sum<M, the current window is too small. Removing positive elements cannot help it reach M, so extend the right endpoint. Line 10 has already incremented j, which is why line 11 adds A[j], not A[j+1]. If j=n, there is no further element to add and the loop can terminate.

If sum≥M, the current window is feasible. Its actual length is j−i+1, but min deliberately stores length minus one, so line 15 compares j−i. Remove A[i] and advance i to look for a shorter feasible window with the same right endpoint. Repeated shrinking examines the best ending-at-j choice before extending again. Positivity ensures that once a left endpoint is discarded, retaining it for later right endpoints cannot improve on a feasible length already considered.

For A=[2,3,1,2] and M=5, the first feasible window is [2,3], length 2. It stores min=1. After shrinking and extending, [3,1,2] is feasible but longer. The final print is 2. If no window reaches M, min stays n and the sentinel print is n+1. If one element alone reaches M, min becomes 0 and the answer is 1; removing that element creates a temporary empty window of sum zero, which safely forces extension or termination because M>0.

Both i and j only increase, giving O(n) time and O(1) auxiliary space. Negative array elements would invalidate the monotonic shrinking argument. The strict comparison at line 6 is essential: equality sum=M already satisfies the requested threshold. Full code and its statement numbering are reconstructed from the paper pp8–9, where the boxes and assignments remain visible.

Original paper, page 8

2 marks · MCQ
Report issue

Repeated subtraction algorithm

Correctness, Invariants & Design

Question 2.3, GATE 1995: For positive integers X,Y, repeatedly replace the larger by its difference from the smaller until X=Y, then print X. What is computed?
Tap to enlarge
Your answer
Answer & solution

Answer: C: gcd of the original integers (no official key was published)

For X>Y, gcd(X,Y)=gcd(X−Y,Y), because the common divisors are unchanged by subtraction. The symmetric identity holds when Y>X. Thus every loop preserves the original gcd. Both variables remain positive, and their sum strictly decreases on each iteration, so the process terminates. At termination X=Y, whose gcd is that common value. The printed result is therefore the original gcd, not their lcm or the quotient of a single division.

Original paper, page 3

Descriptive
Report issue

In-place cyclic rotation

Correctness, Invariants & Design

Question 7, GATE 1994: A[0..n−1] contains n integers. Shift it cyclically left K places, 1≤K≤n−1, in linear time without another array. Fill the five blanks in this skeleton.
min:=n; i:=0;
while ___ do begin
  temp:=A[i]; j:=i;
  while ___ do begin
    A[j]:=___; j:=(j+K) mod n;
    if j<min then min:=j;
  end;
  A[(n+i-K) mod n]:=___;
  i:=___;
end;
Tap to enlarge
Answer & solution

Answer: In order: i<min; (j+K) mod n ≠ i; A[(j+K) mod n]; temp; i+1. (no official key was published)

1. The desired assignment is new A[j]=old A[(j+K) mod n]. Follow this permutation one cycle at a time.

2. Save the first value in temp, copy forward along the cycle, and stop before the next source would be the overwritten start. The last destination is (i−K) mod n, where temp belongs.

3. Let g=gcd(n,K). The first cycle contains precisely the indices divisible by g. Its smallest positive visited index is g, so min becomes g. For K in the given range the cycle has at least two positions.

4. The remaining starts 1,…,g−1 cover the other residue classes. No update makes min smaller than g. After these g cycles the outer loop ends. Each index is assigned once, so time is Θ(n), with O(1) extra storage.

Code

min := n; i := 0
while i < min:
    temp = A[i]; j = i
    while (j + K) % n != i:
        A[j] = A[(j + K) % n]
        j = (j + K) % n
        if j < min: min = j
    A[(n + i - K) % n] = temp
    i = i + 1

Original paper, page 5

5 marks · Descriptive
Report issue

Complete a single-loop matrix maximum

Correctness, Invariants & Design

Question 12, GATE 1993: For integer A[0..n-1,0..n-1], complete four boxes in: max:=[A]; i:=0; j:=0; while [B] do begin if A[i,j]>max then max:=A[i,j]; if [C] then j:=j+1 else begin j:=0; i:=[D] end end. Use a single loop to find the largest entry. The source's comma/semicolon punctuation is defective; boxes A–D are one coordinated question.
Tap to enlarge
Answer & solution

Answer: A=A[0,0]; B=i<n; C=j<n−1; D=i+1 (n>=1). (no official key was published)

For n>=1 choose box A=A[0,0], B=(i<n), C=(j<n-1), D=i+1. Initializing to the first entry rather than 0 is important: all entries may be negative. The fully punctuated Pascal-style segment is:

begin
  max := A[0,0];
  i := 0; j := 0;
  while i < n do
  begin
    if A[i,j] > max then max := A[i,j];
    if j < n-1 then
      j := j+1
    else
    begin
      j := 0;
      i := i+1
    end
  end
end.

The pair (i,j) moves in row-major order: (0,0),(0,1),...,(0,n-1),(1,0),..., (n-1,n-1). At a row's last column, j is reset before proceeding to the next row. After the final element the state becomes (n,0); the guard stops before any invalid A[n,0] access.

Correctness invariant: immediately before processing each cell, max is the maximum of A[0,0] and every previously visited cell. The comparison incorporates the current cell and preserves this property. The rank n*i+j increases by exactly 1 per iteration and begins at 0, so exactly n2 cells are visited. On exit the invariant gives the maximum over the entire array. For n=1 the first entry is compared with itself once and the program exits correctly. Time is Theta(n2), extra space Theta(1). The n=0 case has no maximum and must be rejected or handled outside this segment; the printed task implicitly needs a nonempty array.

Original paper, page 11

2 marks · Other
Report issue

Evenness as a loop invariant

Correctness, Invariants & Design

Question 1(vi), GATE 1991: Pascal enters the loop only if i mod 2=0. While i≥0, it replaces i by i div 2, then subtracts 1 if the new i is odd, otherwise subtracts 2. Give an invariant.
Question 1(vi), GATE 1991: Pascal enters the loop only if i mod 2=0. While i≥0, it replaces i by i div 2, then subtracts 1 if the new i is odd, otherwise subtracts 2. Give an invariant.
Tap to enlarge
Answer & solution

Answer: i is even at each loop test (no official key was published)

The outer test establishes evenness before the first loop test. Let j be the quotient after the division in an iteration. If j is odd, j−1 is even; if j is even, j−2 is even. Thus either branch reestablishes the invariant regardless of the parity produced by division. Nonnegativity is the loop guard, not an invariant after the body: for i=0 the body produces −2 and terminates. An even negative initial value skips the loop altogether. The invariant states a preserved property, not a complete description of all reachable values.

Original paper, page 1

2 marks · MSQ
Report issue

Integer square-root loop

Correctness, Invariants & Design

Question 3(viii), GATE 1991: GFG initializes i=0 and repeats i:=i+1 while i*i≤N, then returns i. Forum instead prints i*i<N. Determine the return for positive N.
Question 3(viii), GATE 1991: GFG initializes i=0 and repeats i:=i+1 while i*i≤N, then returns i. Forum instead prints i*i<N. Determine the return for positive N.
Question 3(viii), GATE 1991: GFG initializes i=0 and repeats i:=i+1 while i*i≤N, then returns i. Forum instead prints i*i<N. Determine the return for positive N.
Tap to enlarge
Select all that apply
Answer & solution

Answer: B: floor(√N)+1 (no official key was published)

For the non-strict the guard, the loop exits at the smallest integer i whose square exceeds N. That is floor(√N)+1, including a perfect square N=k², which returns k+1. For nonsquares both expressions coincide. For example, N=4 distinguishes 3 from 2. The source change therefore matters and is not a harmless formatting variation. This arithmetic analysis assumes i*i and the increment do not overflow the Pascal integer range.

Original paper, page 3