Data Structures & AlgorithmsModerateProduct Company SDE pattern
What is printed? (trie: count distinct prefixes / nodes)
What is printed? (trie: count distinct prefixes / nodes)
words = ["tea", "ten", "to", "inn", "in", "i"]
root, nodes = {}, 0
for w in words:
t = root
for ch in w:
if ch not in t: t[ch] = {}; nodes += 1
t = t[ch]
t['$'] = True
print(nodes, len(root))- A. 8 2
- B. 11 2
- C. 8 3
- D. 14 2
Correct answer: A. 8 2
Shared prefixes reuse nodes: tea adds t, e, a (3); ten adds only n (4); to adds o (5); inn adds i, n, n (8); in and i add nothing, they just mark existing nodes as word ends. The root has two children, t and i. 14 letters were inserted but only 8 nodes exist. Insert and search are O(word length).
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
- What is printed? (count connected components with DFS on an adjacency list) python n = 8 edges = [(0, 1), (1, 2), (3, 4), (5, 6), (6, 7)…
- Floyd–Warshall on 4 vertices. What is the shortest distance from 0 to 3, and from 3 to 1? python INF = float('inf') d = [[0, 3, INF, 7]…
- Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)? python edges = [(0, 1…
- What is printed? (detect a cycle in an undirected graph with union-find) python def hascycle(n, edges): p = list(range(n)) def f(x): while…
- What is printed? (number of paths from source to target in a DAG with memoisation) python from functools import lrucache g = {0: [1, 2…
- What is printed? (longest path in a DAG using topological order) python g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1)…