Question

Consider the following ANSI-C function.

int func(int start, int end){
    int length=end+1-start;
    if((length<1)||(start<0)||(end<0)){ return(0); }
    if(length%3==0){
        return(func(start+1, end));
    } else if(length%3==1){
        return(1+func(start, end-1));
    } else {
        return(func(start+2, end));
    }
}

The maximum possible value that can be returned from this function is ____________. (answer in integer)

Note: Ignore syntax errors (if any) in the function.

Official answer and solution
Official answer
1
From
Official GATE 2026 answer key

Solution

Track how length = end + 1 - start changes modulo 3 in each recursive branch.

Let L=length=end+1−startL = \text{length} = \text{end} + 1 - \text{start}. Whenever L<1L < 1 or start<0\text{start} < 0 or end<0\text{end} < 0, func returns 00. For L≥1L \ge 1:

  • If L≡2(mod3)L \equiv 2 \pmod 3: the else branch calls func(start + 2, end), which reduces LL by 22 without adding to the return value, giving L′=L−2≡0(mod3)L' = L - 2 \equiv 0 \pmod 3.
  • If L≡0(mod3)L \equiv 0 \pmod 3: the first branch calls func(start + 1, end), which reduces LL by 11 without adding to the return value, giving L′=L−1≡2(mod3)L' = L - 1 \equiv 2 \pmod 3.
    Thus any call starting with L≡0L \equiv 0 or L≡2(mod3)L \equiv 2 \pmod 3 alternates between 0(mod3)0 \pmod 3 and 2(mod3)2 \pmod 3 (decreasing LL by 11, then 22, then 11, ...) until L≤0L \le 0, returning 00!
  • If L≡1(mod3)L \equiv 1 \pmod 3: the else if branch returns 1 + func(start, end - 1), which adds 11 and reduces LL by 11 to L′=L−1≡0(mod3)L' = L - 1 \equiv 0 \pmod 3. By the case above, the recursive call with L′≡0(mod3)L' \equiv 0 \pmod 3 always returns 00!

Therefore, func returns at most 1+0=11 + 0 = 1 for any inputs.

Final answer

1

Common trap

Assuming the length % 3 == 1 branch can be visited multiple times when in fact it transitions immediately to length % 3 == 0, which then cycles between 00 and 2(mod3)2 \pmod 3.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2026 Computer Science and Information Technology - Session 2 (CS2)
Question
61 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.