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)- A. 16 15 an
- B. 22 21 ana
- C. 16 15 ana
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)? python from collections…
- Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed? python LOG = 4…
- Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct…
- Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?…
- Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make…
- Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s)…