Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Replace each word of a sentence by its shortest root from a dictionary (if any root is a prefix).
Problem: Replace each word of a sentence by its shortest root from a dictionary (if any root is a prefix).
def replace(roots, sentence):
trie = {}
for r in roots:
t = trie
for ch in r: t = t.setdefault(ch, {})
t['$'] = r
out = []
for w in sentence.split():
t = trie; rep = w
for ch in w:
if ch not in t: break
t = t[ch]
if '$' in t: rep = t['$']; break
out.append(rep)
return " ".join(out)
print(replace(["cat", "ca", "bat", "rat"], "the cattle was rattled by the battery"))What is printed?- A. the ca was rat by the bat
- B. the cat was rat by the bat
- C. the cattle was rattled by the battery
- D. the ca was rattled by the bat
Correct answer: A. the ca was rat by the bat
Walking the trie letter by letter stops at the first complete root, so the shortest root wins: 'cattle' → 'ca' (not 'cat'), 'rattled' → 'rat', 'battery' → 'bat'.
More Coding Interview Problems questions
- Problem: Find the shortest palindrome obtainable by adding characters only in FRONT of s, using the KMP failure function of s + '#' +…
- Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last…
- Problem: Delete the fewest characters so that no two letters have the same (nonzero) frequency. python from collections import Counter def…
- Problem: An array of n + 1 integers holds values 1..n with exactly one value repeated (possibly several times). Find it in O(1) extra…
- Problem: Find all values appearing more than ⌊n/3⌋ times with the extended Boyer–Moore vote (two candidates), then verify. python def…
- Find the bug: Boyer–Moore majority vote is used WITHOUT the verification pass on an array that may have no majority. python def…