Longest Word With All Prefixes - Problem

Given an array of strings words, find the longest string in words such that every prefix of it is also in words.

For example, let words = ["a", "app", "ap"]. The string "app" has prefixes "ap" and "a", all of which are in words.

Return the string described above. If there is more than one string with the same length, return the lexicographically smallest one, and if no string exists, return "".

Input & Output

Example 1 — Basic Case
$ Input: words = ["a", "app", "ap"]
Output: "app"
💡 Note: The word "app" has prefixes "a" and "ap", both exist in the array. "app" is the longest such word.
Example 2 — Multiple Valid Words
$ Input: words = ["w", "wo", "wor", "worl", "world"]
Output: "world"
💡 Note: "world" has all prefixes "w", "wo", "wor", "worl" in the array. It's the longest valid word.
Example 3 — No Valid Word
$ Input: words = ["abc", "def", "ghi"]
Output: ""
💡 Note: No word has all its prefixes in the array ("abc" needs "a", "ab" but they don't exist).

Constraints

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

Visualization

Tap to expand
Longest Word With All PrefixesInput: ["a", "app", "ap"]"a""app""ap"length: 1length: 3length: 2✓ No prefixes to check✓ Prefix "a" exists✓ Prefix "a" exists✓ Prefix "ap" existsResult: "app"Longest with all prefixes
Understanding the Visualization
1
Input
Array of words: ["a", "app", "ap"]
2
Process
Check which words have all prefixes present
3
Output
Return longest valid word: "app"
Key Takeaway
🎯 Key Insight: Only words that can be built character-by-character from existing shorter words are valid candidates
Asked in
Google 25 Amazon 18 Microsoft 12
23.5K Views
Medium Frequency
~25 min Avg. Time
890 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