Data Structures & AlgorithmsVery hardProduct company OA

Problem: Find the longest string that is a prefix of s, a suffix of s, and also occurs somewhere strictly inside (not as the prefix or the suffix occurrence). Uses the Z-function.

Problem: Find the longest string that is a prefix of s, a suffix of s, and also occurs somewhere strictly inside (not as the prefix or the suffix occurrence). Uses the Z-function.
def z(s):
    n = len(s); z = [0] * n; l = r = 0
    for i in range(1, n):
        if i < r: z[i] = min(r - i, z[i - l])
        while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1
        if i + z[i] > r: l, r = i, i + z[i]
    return z
def best(s):
    n = len(s); zz = z(s)
    for L in range(n - 1, 0, -1):
        if zz[n - L] == L and any(zz[j] >= L for j in range(1, n - L)):
            return s[:L]
    return ""
print(best("fixprefixsuffix"), repr(best("abcab")), best("aaaa"), best("abababab"))
What is printed?
  1. A. fix 'ab' aaa ababab
  2. B. fix '' a ab
  3. C. fix '' aa abab
  4. D. suffix '' aa abab

Correct answer: C. fix '' aa abab

A suffix starting at n − L is a border iff z[n − L] = L. It also occurs strictly inside iff some j in 1..n − L − 1 has z[j] ≥ L. Try lengths from long to short. 'fix' appears at 3 (pre-fix) → 'fix'. abcab: border 'ab' never appears in the middle → ''. aaaa: 'aaa' is a border but has no interior start, 'aa' starts at 1 → 'aa'. abababab: 'ababab' fails (only starts 0 and 2 = suffix), 'abab' starts at 2 → 'abab'. O(n²) worst-case as written; with a prefix-max of z it is O(n).

More Coding Interview Problems questions

Exams that ask this topic