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?- A. fix 'ab' aaa ababab
- B. fix '' a ab
- C. fix '' aa abab
- 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
- Problem: Count pairs i < j with a[i] XOR a[j] < 6 using a binary trie that stores subtree counts (4-bit values). python def countless(a…
- Problem: For every contiguous block, score = (minimum of the block) × (sum of the block). Return the maximum score using a monotonic stack…
- Problem: Find the shortest substring of s that contains t as a SUBSEQUENCE (leftmost if several). Two pointers: scan forward to complete…
- Problem: Count monotone paths (right/down) in a grid with blocked cells. The first version builds the table as [[0] C] R – every row is…
- Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again. python…
- Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches…