GATE Assistant

Past questions › Computer Science and Information Technology › GATE 2024 set2

GATE 2024 set2 · CS · MCQ · 2 marks · Programming and Data Structures › C Programming Fundamentals

GATE 2024 set2 Computer Science and Information Technology question: Consider an array X that contains n positive integers. A subarray of X is defined to be…

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

The C code snippet given below has been written to compute the length of the longest subarray of X that contains at most two distinct integers. The code has two missing expressions labelled and .

int first=0, second=0, len1=0, len2=0, maxlen=0;
for (int i=0; i < n; i++) {
  if (X[i] == first) {
    len2++; len1++;
  } else if (X[i] == second) {
    len2++;
    len1 =   (P)   ;
    second = first;
  } else {
    len2 =   (Q)   ;
    len1 = 1; second = first;
  }
  if (len2 > maxlen) {
    maxlen = len2;
  }
  first = X[i];
}

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

(Hint: At the end of the -th iteration, the value of len1 is the length of the longest subarray ending with X[i] that contains all equal values, and len2 is the length of the longest subarray ending with X[i] that contains at most two distinct values.)

  1. (A)

    len1+1 len2+1

  2. (B)

    1 len1+1

  3. (C)

    1 len2+1

  4. (D)

    len2+1 len1+1

Show answer

Official answer: B

Practise this question with exam-style marking

Discussion

No discussion yet.

Join the discussion