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 Prefixes INPUT words array: "a" "app" "ap" HashSet Created: "a" "ap" "app" ALGORITHM STEPS 1 Build HashSet Store all words for O(1) lookup 2 Sort Words By length desc, then lexically 3 Check Each Word Verify all prefixes exist 4 Return First Valid Longest with all prefixes Checking "app": Prefix "a" in set? OK Prefix "ap" in set? OK All prefixes found! FINAL RESULT Winner found: "app" Length: 3 characters Prefix Chain: "a" "ap" "app" Output: "app" Key Insight: Using a HashSet enables O(1) prefix lookup. For each word, we check all its prefixes (O(L) where L is word length). Total time complexity: O(N * L) where N is number of words. Sorting by length ensures we find the longest valid word first. TutorialsPoint - Longest Word With All Prefixes | Hash Set Optimization Approach
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