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?
  1. A. the ca was rat by the bat
  2. B. the cat was rat by the bat
  3. C. the cattle was rattled by the battery
  4. 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

Exams that ask this topic