ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def pi(s):
    p = [0] * len(s)
    k = 0
    for i in range(1, len(s)):
        while k and s[i] != s[k]:
            k = p[k - 1]
        if s[i] == s[k]:
            k += 1
        p[i] = k
    return p
print(pi('aabaaab'), pi('abcab')[-1])
  1. A. [0, 1, 0, 1, 2, 2, 3] 2
  2. B. [0, 1, 0, 1, 2, 3, 3] 2
  3. C. [0, 1, 0, 1, 2, 2, 3] 1
  4. D. [0, 0, 0, 1, 2, 2, 3] 2

Correct answer: A. [0, 1, 0, 1, 2, 2, 3] 2

The prefix function gives, for each position, the length of the longest proper prefix that also ends there. For aabaaab it rises 1, 0, 1, 2, 2, 3, and for abcab the last value is 2 because ab repeats.

More Python Programming questions

Exams that ask this topic