GATE / CS ARCHIVE

GATE CSE 2024 SET 2 / QUESTION 42

Maintain the one-run and two-value suffix invariants

Algorithms · Correctness, Invariants & Design · Full GATE CSE 2024 Set 2 paper

GATE 2024 Set 2, Q42 2 marks · MCQ
Report issue

Correctness, Invariants & Design

Question 42, GATE 2024: For positive X[0..n−1], initialize first=second=len1=len2=maxlen=0. For each v=X[i]: if v==first increment both len1,len2; else if v==second increment len2, set len1=P, second=first; else set len2=Q, len1=1, second=first. Update maxlen=max(maxlen,len2), then first=v. len1 is the equal-value suffix length; len2 is the suffix length with at most two distinct values. Choose P,Q: A len1+1,len2+1; B 1,len1+1; C 1,len2+1; D len2+1,len1+1.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Approach: Interpret the saved values before the current iteration updates them.

1. Derivation. first is the previous element and len1 is its final equal-value run length. If the next item equals second but differs from first, the final equal run starts anew, so P=1, while the valid two-value suffix extends by one. If a third distinct value arrives, only the previous final run can accompany it; therefore the new two-value suffix has length len1+1, giving Q=len1+1. The assignments update second to the old first. Thus B; positive input values ensure initial zero sentinels are not actual array values.

2. Explanation and checks. For the prefix [1,2,2], len1=2 and len2=3. If the next value is 1, it is the other known value: the two-value suffix grows to 4, but the same-value suffix has length 1. If instead the next value is 3, keeping all three old elements would create three distinct values; only [2,2,3] is legal, of length old len1+1=3. Updating first last preserves the old run value while second is assigned.

Original paper, page 29 · Answer key