Skip to content
Official PYQ · 2026

GATE CS 2026 Set 1 Q51 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the recursive functions represented by the following code segment:

int bar(int n) {
    if (n == 1) return 0;
    else return 1 + bar(n/2);
}
int foo(int n) {
    if (n == 1) return 1;
    else return 1 + foo(bar(n));
}

The smallest positive integer n for which f∘∘(n)\mathrm{f} \circ \circ(\mathrm{n}) returns 55 is ____\_\_\_\_. (answer in integer)

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

View worked solution

Answer: 65536 : 65536

To find the smallest positive integer nn for which foo(n)=5\text{foo}(n) = 5, let us analyze the behavior of both recursive functions.

1. Behavior of bar(n):

  • bar(1)=0\text{bar}(1) = 0
  • For n>1n > 1, bar(n)=1+bar(⌊n/2⌋)\text{bar}(n) = 1 + \text{bar}(\lfloor n/2 \rfloor)

This recurrence computes the floor of the base-2 logarithm: bar(n)=⌊log⁡2n⌋\text{bar}(n) = \lfloor \log_2 n \rfloor.

2. Behavior of foo(n):

  • foo(1)=1\text{foo}(1) = 1
  • For n>1n > 1, foo(n)=1+foo(bar(n))\text{foo}(n) = 1 + \text{foo}(\text{bar}(n))

3. Working Backwards to Minimize nn:

Let nkn_k be the smallest positive integer such that foo(nk)=k\text{foo}(n_k) = k.

  • For k=1k = 1: The smallest value is n1=1n_1 = 1.
  • For k=2k = 2: We need foo(bar(n2))=1\text{foo}(\text{bar}(n_2)) = 1. To minimize n2n_2, we need the smallest bar(n2)=n1=1\text{bar}(n_2) = n_1 = 1.
    ⌊log⁡2n2⌋=1  ⟹  \lfloor \log_2 n_2 \rfloor = 1 \implies smallest n2=21=2n_2 = 2^1 = 2.
  • For k=3k = 3: We need foo(bar(n3))=2\text{foo}(\text{bar}(n_3)) = 2. To minimize n3n_3, we need the smallest bar(n3)=n2=2\text{bar}(n_3) = n_2 = 2.
    ⌊log⁡2n3⌋=2  ⟹  \lfloor \log_2 n_3 \rfloor = 2 \implies smallest n3=22=4n_3 = 2^2 = 4.
  • For k=4k = 4: We need foo(bar(n4))=3\text{foo}(\text{bar}(n_4)) = 3. To minimize n4n_4, we need the smallest bar(n4)=n3=4\text{bar}(n_4) = n_3 = 4.
    ⌊log⁡2n4⌋=4  ⟹  \lfloor \log_2 n_4 \rfloor = 4 \implies smallest n4=24=16n_4 = 2^4 = 16.
  • For k=5k = 5: We need foo(bar(n5))=4\text{foo}(\text{bar}(n_5)) = 4. To minimize n5n_5, we need the smallest bar(n5)=n4=16\text{bar}(n_5) = n_4 = 16.
    ⌊log⁡2n5⌋=16  ⟹  \lfloor \log_2 n_5 \rfloor = 16 \implies smallest n5=216=65536n_5 = 2^{16} = 65536.

Thus, the smallest positive integer nn for which foo(n)\text{foo}(n) returns 55 is 6553665536.

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

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions