Data Structures & AlgorithmsVery hardProduct company OA

All suffixes of 'banana' are inserted into a character trie (a suffix trie). What is printed (trie nodes including the root, distinct non-empty substrings, longest substring that occurs at least twice)?

All suffixes of 'banana' are inserted into a character trie (a suffix trie). What is printed (trie nodes including the root, distinct non-empty substrings, longest substring that occurs at least twice)?
s = "banana"
root, nodes = {}, 1
for i in range(len(s)):
    cur = root
    for ch in s[i:]:
        if ch not in cur: cur[ch] = {}; nodes += 1
        cur = cur[ch]
best = ""
for i in range(len(s)):
    for j in range(i + 1, len(s) + 1):
        sub = s[i:j]
        if s.find(sub, i + 1) != -1 and len(sub) > len(best): best = sub
print(nodes, nodes - 1, best)
  1. A. 16 15 an
  2. B. 22 21 ana
  3. C. 16 15 ana
  4. D. 15 14 nan

Correct answer: C. 16 15 ana

Every root-to-node path in a suffix trie spells a distinct substring and every substring is a prefix of some suffix, so nodes − 1 = number of distinct substrings: 15 (21 substring positions minus 6 duplicates: a×3, n×2, an×2, na×2, ana×2 → 21 − 6 = 15). 'ana' occurs at 1 and 3 (overlapping), so it is the longest repeat; 'nan' occurs once. A naive suffix trie is O(n²) nodes; suffix automata/trees compress it to O(n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic