Skip to content
Official PYQ · 2024

GATE CS 2024 Set 2 Q32 — Algorithm Design: Greedy Techniques

Explain with AI

​​​​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)}.

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 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.)

Choose one option
View worked solution

Answer: B

To find the correct expressions for (P) and (Q), we can analyze the state of the variables at the ii-th iteration using the hint provided:

  • len1 is the length of the longest contiguous subarray ending at X[i]X[i] containing identical elements.
  • len2 is the length of the longest subarray ending at X[i]X[i] containing at most two distinct elements.

Case 1: When X[i] == second

Since X[i]X[i] is equal to second, it is different from first (which is X[i−1]X[i-1]). This means the contiguous block of identical elements ending at X[i]X[i] is broken, and a new contiguous block of identical elements starts at X[i]X[i]. Thus, its length len1 must be reset to 11.

(P)=1\text{(P)} = 1

Case 2: When X[i] is a new element (the else block)

Since X[i]X[i] is different from both first and second, the new subarray ending at X[i]X[i] with at most two distinct elements can only contain X[i]X[i] and the contiguous block of first elements immediately preceding it. The length of this preceding contiguous block is len1. Including the new element X[i]X[i], the new length len2 becomes:

(Q)=len1+1\text{(Q)} = \text{len1} + 1

Thus, the correct option is B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Algorithm Design: Greedy Techniques questions