GATE CS 2024 (Afternoon) — Question 42

Programming in CData Types, Syntax, Control Structures, LoopsMCQ2 marks · −2/3 if wrongHard

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 (P) and (Q).
c
1int first = 0, second = 0, len1 = 0, len2 = 0, maxlen = 0;
2for (int i = 0; i < n; i++) {
3    if (X[i] == first) {
4        len2++; len1++;
5    }
6    else if (X[i] == second) {
7        len 2++;
8        len1 = ____(P)____;
9        second = first;
10    }
11    else {
12        len2 = ____(Q)____;
13        len1 = 1; second = first;
14    }
15    if (len2 > maxlen) {
16        maxlen = len 2;
17    }
18    first = X[i];
19}
20
Which one of the following options gives the CORRECT missing expressions? (Hint: At the end of the \( i^{\text{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
    (P) len1 + 1 (Q) len2 + 1
  2. B
    (P) 1 (Q) len1 + 1
  3. C
    (P) 1 (Q) len2 + 1
  4. D
    (P) len 2 + 1 (Q) len1 + 1
Practise the full 2024-AN paper
Challenge a friend: WhatsApp Telegram
Recommended book · affiliate linkCompilers: Principles, Techniques & ToolsThe "Dragon Book" for parsing, syntax-directed translation and code generation.
Practise more on Data Types, Syntax, Control Structures, LoopsTimed, in the real exam interface · free to start

A GATE question every morning

One real past-paper question every morning for your branch, answer hidden until you tap. Free on Telegram.

Join
Stuck? Ask in the student group