ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (strings are indexed from 0)

What will be the output of the following pseudocode? (strings are indexed from 0)
String p = "ABABCABAB"
Integer f[9], k = 0
f[0] = 0
for (each i from 1 to 8)
    while (k > 0 AND p[i] != p[k])
        k = f[k - 1]
    end while
    if (p[i] == p[k])
        k = k + 1
    end if
    f[i] = k
end for
Print f[3], f[4], f[8]
  1. A. 2 3 3
  2. B. 2 0 4
  3. C. 1 0 4
  4. D. 2 0 5

Correct answer: B. 2 0 4

f[i] is the length of the longest proper prefix of p[0..i] that is also its suffix (the KMP failure table). ABAB → 2 (AB), ABABC → 0, and ABABCABAB → 4 (ABAB). Output 2 0 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic