#720

Longest Word in Dictionary

Medium Trie walk through complete words

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

?The problem

Return the longest word that can be built one letter at a time where every prefix along the way is also a word in the list. On ties, return the alphabetically smallest.

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

◎Understanding

Really asking: the longest word that can be built one letter at a time from other words.

Why this works: in the trie, only walk through nodes that end a word; every prefix is then also a word.

Example: ["w","wo","wor","worl","world"]

w → wo → wor → worl → world ✓

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Checking only that the full word exists, not every prefix.

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