#648

Replace Words

Medium Shortest root in a trie

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Given a list of roots and a sentence, replace every word that starts with a root by the shortest such root.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: replace each word with its shortest root from a dictionary.

Why this works: walk the trie along the word; stop at the first node that ends a root.

Example: roots ["cat", "bat", "rat"], sentence "the cattle was rattled"

cattle → cat, rattled → rat"the cat was rat"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Checking every root against every word with startsWith — O(words × roots × length).

Solve on LeetCode ↗
Complexity
  • Time: O(total characters).
  • Space: O(total root characters).
Topic: Trie
🎬 Episode 97: video coming soon