GeeksforGeeks Medium

Longest Word with All Prefixes

Longest Word with All Prefixes is a GFG problem (Medium). Given an array of lowercase strings words, find the longest string such that every one of its prefixes is also in words.

  • A prefix here means the first 1, 2, 3, … letters, up to the whole word. So "abc" needs "a", "ab" and "abc" in the list.
  • If several valid strings share the longest length, return the alphabetically smallest.
  • If no string is valid, return "".

The practice page titles it Longest Valid Word with All Prefixes, and the function to write is longestValidWord(words).

Constraints
  • 1 <= words.size <= 1000
  • 1 <= words[i].size <= 100
  • Words consist of lowercase English letters
triestring
Open on GeeksforGeeks ↗
02

Intuition

In a trie, the prefixes of a word are exactly the nodes on its path from the root. Insert every word and mark the node where each one ends. Then a word is valid when every node on its path carries an end mark, because each marked node is a prefix that appears in the list as a whole word.

  • Build: one insert per word; words with a shared start share nodes.
  • Check: walk each word from the root and stop at the first unmarked node.
  • Pick: keep the longest valid word, and on equal length the alphabetically smaller one.
How to spot this pattern

"Every prefix must also be present" points to a trie: one walk down a word visits all of its prefixes in order, so the check costs one step per letter.

03

Approach

Try it first

Before reading on, think about where a word's prefixes live in a trie and what extra bit each node needs. Then decide how to break ties without sorting. Aim for time linear in the total number of letters.

1

Build the trie

For each word, walk down from the root, creating a child for each missing letter, and set end = True on the node of the last letter. A node is marked only when some word in the list ends exactly there.

2

Check every prefix of a word

Walk the word again from the root. At each letter, move to the child and require end on it. An unmarked node means that prefix is not in the list, so stop and reject the word.

3

Keep the best word

When a word passes, replace best if the word is longer, or the same length and smaller in dictionary order. Starting from best = "" means the empty answer comes out on its own when nothing passes.

04

Code in Python, C++ and Java

▶1class TrieNode:
▶2 def __init__(self):
▶3 self.children = {}
▶4 self.end = False
▶5 
▶6 
▶7class Solution:
▶8 def longestValidWord(self, words):
▶9 root = TrieNode()
▶10 for w in words:
▶11 node = root
▶12 for ch in w:
▶13 if ch not in node.children:
▶14 node.children[ch] = TrieNode()
▶15 node = node.children[ch]
▶16 node.end = True
▶17 
▶18 best = ""
▶19 for w in words:
▶20 node = root
▶21 ok = True
▶22 for ch in w:
▶23 node = node.children[ch]
▶24 if not node.end:
▶25 ok = False
▶26 break
▶27 if ok and (len(w) > len(best) or (len(w) == len(best) and w < best)):
▶28 best = w
▶29 return best
ends a wordrootainsertabestnone yetinsert 'a' → mark its last node
word'a'
best''
Walk 'a' down from the root, adding 1 new node. The node for its last letter gets the green ends a word mark, so any longer word passing through it knows 'a' is in the list.
ends a wordrootabinsertabbestnone yetinsert 'ab' → mark its last node
word'ab'
best''
Walk 'ab' down from the root, adding 1 new node. The node for its last letter gets the green ends a word mark, so any longer word passing through it knows 'ab' is in the list.
ends a wordrootabcinsertabcbestnone yetinsert 'abc' → mark its last node
word'abc'
best''
Walk 'abc' down from the root, adding 1 new node. The node for its last letter gets the green ends a word mark, so any longer word passing through it knows 'abc' is in the list.
ends a wordrootabcbinsertbbestnone yetinsert 'b' → mark its last node
word'b'
best''
Walk 'b' down from the root, adding 1 new node. The node for its last letter gets the green ends a word mark, so any longer word passing through it knows 'b' is in the list.
ends a wordrootabcbcdinsertbcdbestnone yetinsert 'bcd' → mark its last node
word'bcd'
best''
Walk 'bcd' down from the root, adding 2 new nodes. The node for its last letter gets the green ends a word mark, so any longer word passing through it knows 'bcd' is in the list.
ends a wordrootabcbcdchecka✓bestaevery prefix is a word → 'a' is the new best
word'a'
best'a'
Every node on the path is marked, so 'a' is valid. It is the first valid word, so it becomes the best.
ends a wordrootabcbcdchecka✓bbesta'a' is a word → keep walking
word'ab'
best'a'
The node for 'a' carries the end mark, so this prefix is in the list. Move on to the next letter.
ends a wordrootabcbcdchecka✓b✓bestabevery prefix is a word → 'ab' is the new best
word'ab'
best'ab'
Every node on the path is marked, so 'ab' is valid. It is longer than 'a', so it takes over.
ends a wordrootabcbcdchecka✓bcbestab'a' is a word → keep walking
word'abc'
best'ab'
The node for 'a' carries the end mark, so this prefix is in the list. Move on to the next letter.
ends a wordrootabcbcdchecka✓b✓cbestab'ab' is a word → keep walking
word'abc'
best'ab'
The node for 'ab' carries the end mark, so this prefix is in the list. Move on to the next letter.
ends a wordrootabcbcdchecka✓b✓c✓bestabcevery prefix is a word → 'abc' is the new best
word'abc'
best'abc'
Every node on the path is marked, so 'abc' is valid. It is longer than 'ab', so it takes over.
ends a wordrootabcbcdcheckb✓bestabcvalid, but 'abc' stays best
word'b'
best'abc'
'b' is valid too, but it is shorter than 'abc', so the best word does not change.
ends a wordrootabcbcdcheckb✓cdbestabc'b' is a word → keep walking
word'bcd'
best'abc'
The node for 'b' carries the end mark, so this prefix is in the list. Move on to the next letter.
ends a wordrootabcbcdcheckb✓c✗dbestabc'bc' is not a word → reject 'bcd'
word'bcd'
best'abc'
The node for 'bc' has no end mark, so 'bc' is not in the list. One missing prefix is enough to rule out 'bcd'; the walk stops here.
ends a wordrootabcbcdcheckbestabcreturn 'abc'
word—
best'abc'
All words are checked. 'abc' is the longest word whose every prefix is in the list, and the alphabetical tie-break has already been applied.
05

Common pitfalls

Checking that the path exists instead of the end marks

✗ Wrong
node = node.children.get(ch)
if node is None:
    ok = False
✓ Right
node = node.children[ch]
if not node.end:
    ok = False

Every word's own path exists once it is inserted, so this test passes everything. On ["a", "apple"] it returns "apple", though "ap", "app" and "appl" are missing; the right answer is "a".

Letting a later word win a tie

✗ Wrong
if ok and len(w) >= len(best):
✓ Right
if ok and (len(w) > len(best) or
           (len(w) == len(best) and w < best)):

With >=, the last valid word of the top length wins, whatever its spelling. On ["a", "b"] it returns "b" instead of "a".

06

Edge cases

No word is valid, e.g. ["cat", "cats"]

Both walks stop at the first node, because "c" is not in the list. best never changes and the function returns "".

07

Complexity

Time
O(S)
Space
O(S)
S is the total number of letters in all words. Each word is walked twice, once to insert and once to check, and a tie comparison costs at most one word length. The trie has at most S nodes.
08

Longest Word with All Prefixes FAQ

Can you solve it without a trie?

Yes. Put every word in a hash set, then for each word test w[:1], w[:2], … against the set. Building each prefix string costs up to its length, so one word of length L costs O(L²) instead of O(L). With words of up to 100 letters that still runs fast; the trie just avoids rebuilding the same prefixes.

LeetCode 1858 has the same name. Is it the same problem?

Yes, it is the same task (a premium problem there), with larger limits: up to 10⁵ letters in total. The trie solution above handles those limits unchanged, since it is linear in the total letter count.

How is this different from Longest Word in Dictionary?

Longest Word in Dictionary (LeetCode 720) asks for the longest word that can be built one letter at a time from other words in the list. That is the same condition as every prefix being present, with the same tie-break, so this trie code solves it too once the method is renamed to longestWord.