Data Structures & AlgorithmsModerateProduct Company SDE · trie round
Problem: Words apple, app, apt, bat, banana are stored in a trie that keeps a count of words passing through each node. What does the code print for prefixes 'ap', 'ban' and 'x'?
Problem: Words apple, app, apt, bat, banana are stored in a trie that keeps a count of words passing through each node. What does the code print for prefixes 'ap', 'ban' and 'x'?
words = ['apple', 'app', 'apt', 'bat', 'banana']
trie = {}
for w in words:
node = trie
for ch in w:
node = node.setdefault(ch, {})
node['#'] = node.get('#', 0) + 1
def cnt(p):
node = trie
for ch in p:
if ch not in node:
return 0
node = node[ch]
return node.get('#', 0)
print(cnt('ap'), cnt('ban'), cnt('x'))What is printed?- A. 2 1 0
- B. 3 2 0
- C. 3 1 1
- D. 3 1 0
Correct answer: D. 3 1 0
Prefix 'ap' is shared by apple, app and apt, prefix 'ban' only by banana, and 'x' by nothing. The count is stored at each node, so a prefix query is O(length).
More Coding Interview Problems questions
- Problem: The longest subarray with equally many 0s and 1s of a = [0, 1, 0, 0, 1, 1, 0] is needed. Run the prefix-balance code and print…
- Problem: Find the 3 smallest pair sums from A = [1, 7, 11] and B = [2, 4, 6], using a heap that starts with each A element paired with…
- Problem: An undirected connected graph has an Euler circuit (a closed walk using every edge exactly once) if and only if which condition…
- Problem: Using 2D prefix sums on M = [[1,2,3],[4,5,6],[7,8,9]], what is the sum of the rectangle with rows 1..2 and columns 1..2…
- Problem: How many pairs (i < j) of a = [1, 2, 3, 4, 5, 6, 7] have a[i] + a[j] divisible by 4? python a = [1, 2, 3, 4, 5, 6, 7] print(sum(1…
- Problem: Count the subarrays of a = [10, 5, 2, 6] whose product is strictly less than k = 100. python def cnt(a, k): if k <= 1: return 0 p…