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?- A. 3 True; 5 False; 5 True;
- B. 3 False; 3 False; 1 False;
- C. 3 False; 5 False; 4 False;
- 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
- 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…
- 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…