ProgrammingVery hardGoldman Sachs OA · Infosys SP

What will be the output of the following pseudocode? (substring(s, i, k) is the k characters starting at index i; / is integer division; + joins strings)

What will be the output of the following pseudocode? (substring(s, i, k) is the k characters starting at index i; / is integer division; + joins strings)
Function f(String s)
    Integer n = length(s)
    if (n <= 2)
        return s
    end if
    return f(substring(s, n / 2, n - n / 2)) + f(substring(s, 0, n / 2))
End Function
Print f("ABCDEFG")
  1. A. GFEDCBA
  2. B. DEFGABC
  3. C. FGDEBCA
  4. D. FGBCDEA

Correct answer: C. FGDEBCA

Each call puts the second half before the first half, but pieces of length ≤ 2 are left as they are. f("DEFG") = f("FG") + f("DE") = FGDE and f("ABC") = f("BC") + f("A") = BCA, so the output is FGDEBCA. A full reversal (GFEDCBA) would need the recursion to go down to single letters.

More Pseudocode and Code Tracing questions

Exams that ask this topic