Longest Word in Dictionary - Problem

Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.

If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

Note that the word should be built from left to right with each additional character being added to the end of a previous word.

Input & Output

Example 1 — Basic Building
$ Input: words = ["w","wo","wor","worl","world"]
Output: "world"
💡 Note: "world" can be built one character at a time: "w" → "wo" → "wor" → "worl" → "world". All intermediate words exist in the dictionary.
Example 2 — Lexicographic Tie
$ Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
💡 Note: Both "apple" and "apply" can be built (a → ap → app → appl → apple/apply), but "apple" is lexicographically smaller.
Example 3 — No Valid Words
$ Input: words = ["hello","world"]
Output: ""
💡 Note: Neither word can be built step by step. "hello" needs "h", "he", "hel", "hell" which don't exist. Same for "world".

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 30
  • words[i] consists of lowercase English letters.

Visualization

Tap to expand
Longest Word in Dictionary DFS with Memoization Approach INPUT Dictionary Words Array "w" "wo" "wor" "worl" "world" Build HashSet for O(1) lookup HashSet {"w", "wo", "wor", "worl", "world"} Words must build char by char: w --> wo --> wor --> worl --> world [0] [1] [2] [3] [4] ALGORITHM STEPS 1 Build HashSet Store all words for O(1) lookup 2 Sort Words By length (desc), then lexically 3 DFS Check Each Word Verify all prefixes exist 4 Memoize Results Cache valid prefix chains DFS for "world" world worl wor wo w OK OK OK OK OK FINAL RESULT Longest buildable word found: "world" Length: 5 characters Complete Build Chain: w --> wo --> wor --> worl --> world Output: "world" Key Insight: A word can only be built if all its prefixes exist in the dictionary. DFS explores each word by recursively checking if prefix[0:len-1] exists. Memoization caches results to avoid recomputing the same prefix chains. Time: O(n * L), Space: O(n * L) where L = max word length. TutorialsPoint - Longest Word in Dictionary | DFS with Memoization
Asked in
Google 42 Amazon 28 Microsoft 18 Facebook 15
58.2K Views
Medium Frequency
~25 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen