GATE CS 2024 Set 2 — Question 42

Go beyond PYQs with Success TrackerAI-powered personalised practice and doubt support. Unlimited practice on eligible plans; AI usage limits apply.
MCQ+2 / -0.67HardArrays & Strings in CC ProgrammingProgramming & Data StructuresArray Operations (1D, 2D)Arrays & Strings

Programming & Data Structures → Arrays & Strings → Array Operations (1D, 2D)

Last updated

Question

Consider an array XX that contains nn positive integers. A subarray of XX 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 XX that contains at most two distinct integers. The code has two missing expressions labelled (P)(P) and (Q)(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 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.)
Your answer

Choose one option, then check your answer.

The solution stays hidden until you check.

Continue learning with Success Tracker

A step still unclear? Work through it with support

Use Success Tracker to ask about the reasoning, then try another GATE CS question to check your understanding.

AI-powered practice· Unlimited practice on eligible plans
PYQs with solutions
Attempt available previous-year questions, then compare your reasoning with the worked solution. Coverage varies by stream.
Practice that adapts
Choose a topic, work on weaker areas and bookmark questions to revisit. Your attempts feed your progress tracking.
AI doubt support
Ask follow-up questions about a step or concept while practising, instead of stopping at the final answer.

Unlimited practice is available on eligible plans. Free practice and AI usage have limits; check the current plan allowances before choosing.

This page stays readable without an account. AI responses can be wrong; check them against the solution and source material.

More questions on Arrays & Strings