Data Structures & AlgorithmsVery hardProduct company OA

Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per divides n.

Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per divides n.
def pi(s):
    p = [0] * len(s)
    for i in range(1, len(s)):
        k = p[i - 1]
        while k and s[i] != s[k]: k = p[k - 1]
        if s[i] == s[k]: k += 1
        p[i] = k
    return p
for s in ["abcabcab", "abaababa", "aaaab"]:
    n = len(s); per = n - pi(s)[-1]
    print(per, n % per == 0, end="; ")
print()
What is printed?
  1. A. 3 True; 5 False; 5 True;
  2. B. 3 False; 3 False; 1 False;
  3. C. 3 False; 5 False; 4 False;
  4. D. 3 False; 5 False; 5 True;

Correct answer: D. 3 False; 5 False; 5 True;

π[n − 1] is the longest proper border; a border of length b means s[i] = s[i + n − b] for all valid i, i.e. a period of n − b. abcabcab has border 'abcab'(5) → period 3, but 8 is not a multiple of 3, so it is a prefix of (abc)^∞ rather than a power. abaababa: border 'aba' → period 5, not a power. aaaab: no border → period 5 = n, trivially a power (one copy). 3 True wrongly assumes a period always tiles the string.

More Coding Interview Problems questions

Exams that ask this topic