Skip to main content

GATE CSE 2024Algorithms › Greedy Method, Dynamic Programming & Algorithm Design TechniquesVerified

GATE CSE 2024 PYQ: ​​​​Consider an array X \mathrm{X} X that contains n \mathrm{n} n positive integers. A subarray of X…

​​​​Consider an array X\mathrm{X} that contains n\mathrm{n} positive integers. A subarray of X\mathrm{X} is defined to be a sequence of array locations with consecutive indices.

The C\mathrm{C} code snippet given below has been written to compute the length of the longest subarray of X\mathrm{X} that contains at most two distinct integers. The code has two missing expressions labelled (P)\text{(P)} and (Q)\text{(Q)}.

  1. int first=0, second=0, len1=0, len2=0, maxlen=0;
  2. for (int i=0; i < n; i++) {
  3. if (X[i] == first) {
  4. len2++; len1++;
  5. } else if (X[i] == second) {
  6. len2++;
  7. len1 = (P);
  8.  
  9. second = first;
  10. } else {
  11. len2 = (Q);
  12. len1 = 1; second = first;
  13. }
  14. if (len2 > maxlen) {
  15. maxlen = len2;
  16. }
  17. first = X[i];
  18. }

Which one of the following options gives the CORRECT missing expressions?

(Hint: At the end of the ii-th iteration, the value of len1len 1 is the length of the longest subarray ending with X[i]\mathrm{X}[i] that contains all equal values, and len2len 2 is the length of the longest subarray ending with X[i]\mathrm{X}[i] that contains at most two distinct values.)

  1. A
    (P) len1+1\text{(P) } \text{len} 1+1       (Q) len2+1\text{(Q) } \text{len} 2+1
  2. B
    (P) 1\text {(P) } 1                    (Q) len1+1\text{(Q) } \text{len} 1+1
    Correct answer
  3. C
    (P) 1\text{(P) } 1                    (Q) len2+1\text{(Q) } \text{len} 2+1
  4. D
    (P) len2+1\text{(P) } \text{len} 2+1       (Q) len1+1\text{(Q) } \text{len} 1+1

Answer

(B) (P) 1 \text {(P) } 1 (P) 1 (Q) len 1 + 1 \text{(Q) } \text{len} 1+1 (Q) len 1 + 1

Approach

Track the two distinct values currently allowed in the subarray using first and second, and maintain len1 (all-equal streak ending at i) and len2 (at most two distinct values ending at i). Analyse the three possible relations between X[i] and the tracked values to fill P and Q.

The code maintains first as the most recent value and second as the other value in the current two-distinct subarray. The branch X[i]==second starts a new all-equal streak, so P = 1. The branch where X[i] is a third distinct value should extend the previous all-equal streak by the new element, so Q = len1 + 1. Therefore option B is correct.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.