Question
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).
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 i-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.)
Official answer and solution
- Official answer
- B
- From
- Official GATE 2024 answer key
Solution
Use the loop invariant for len1 (length of the trailing run of first = X[i-1]) and len2 (length of the longest two-value suffix ending at X[i]).
At the start of the i-th iteration (before first = X[i] at the bottom of the loop), first holds X[i-1], len1 is the length of the contiguous block of elements equal to first ending at i - 1, and second holds the other distinct value immediately preceding that block:
- Expression
(P)(else if (X[i] == second)): SinceX[i] != first, a new contiguous run ofX[i]begins at indexi. Thus the length of the longest subarray ending atX[i]with all equal values islen1 = 1, so(P)is1. - Expression
(Q)(else, whenX[i]is a new third value): Any subarray ending atX[i]with at most two distinct values can only includeX[i]and the immediately preceding contiguous block offirst(of lengthlen1), since including any element before that block would introducesecond(a third distinct value). Thuslen2 = len1 + 1, so(Q)islen1+1.
Option (B)
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2024 Computer Science and Information Technology - Set 2 (CS2)
- Question
- 42 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.