Longest Dictionary Word Ending With a Given Tail
Data Structure DesignAuto-graded · 22 test casesLast updated
Answer batches of suffix queries over a word list, returning the longest match with lexicographic tie-breaking, using a reversed-word trie with cached best words.
Suffix Lookup Service
You are given a dictionary of words and a batch of queries. Each query supplies a tail string. For each query, report the best dictionary word that ends with that tail.
Function inputs
words: the list of dictionary words. It may be empty, and it may contain duplicates (a duplicate behaves like a single copy of the word).operations: a list of operation names, one per query, in order.arguments: a list parallel tooperations. Entryiis a list whose first element,arguments[i][0], is the tail string for queryi. Any further elements are ignored.
Operation names
The only valid operation name is the exact string "find_best_word". If any entry of operations is a different string, the function must raise a ValueError and return nothing. The queries do not change the dictionary, so each query is answered independently against the full words list.
What to return
Return a list of strings with exactly one answer per query, in the same order as operations.
For a query with tail t, the candidates are all words w in words for which w.endswith(t) is true. Choose the answer as follows:
- If there are no candidates, the answer is the empty string
"". - Otherwise, the answer is the candidate with the greatest length.
- If several candidates share that greatest length, the answer is the one that is smallest in standard Python string ordering (
<onstr, which for lowercase letters is ordinary alphabetical order).
Further clarifications:
- A word equal to the tail itself is a valid candidate.
- A word shorter than the tail can never be a candidate.
- The answer is always an actual word from
words, returned exactly as it appears there. - A tail is matched only at the end of a word. A tail occurring elsewhere in the word does not count.
- If
wordsis empty, every answer is"". - If the tail is the empty string, every word ends with it, so the answer is the best word in the whole dictionary under rules 2 and 3 (or
""if the dictionary is empty).
Constraints
- At most 50,000 words.
- The total number of characters across all words is at most 1,000,000.
- Each tail has length between 1 and 100 (the empty-tail rule above is defined for completeness).
- Words and tails contain only lowercase English letters.
- The same dictionary serves every query in the batch, so the solution should be efficient across many queries.
Examples
Example 1
Input: longest_word_with_tail(['apple', 'maple', 'le', 'banana', 'tale'], ['find_best_word', 'find_best_word'], [['le'], ['ana']])
Output: ['apple', 'banana']
Example 2
Input: longest_word_with_tail([], ['find_best_word', 'find_best_word'], [['x'], ['a']])
Output: ['', '']
Example 3
Input: longest_word_with_tail(['cat', 'dog', 'catalog', 'log'], ['find_best_word', 'find_best_word', 'find_best_word'], [['at'], ['og'], ['z']])
Output: ['cat', 'catalog', '']
Hints
Hint 1
A word ends with a tail exactly when the reversed tail is a prefix of the reversed word. Which data structure is built for prefix lookups?
Hint 2
Scanning every matching word for each query is too slow. Store at each trie node the best word among all words passing through it, so a query only reads one stored value.
Hint 3
Compare candidates by length first (longer wins), then alphabetically (smaller wins). Return an empty string when the walk falls off the trie, rather than the best of the partial path. Also validate operation names and raise ValueError for unknown ones.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A word ends with a tail t exactly when reverse(t) is a prefix of reverse(word). So we insert every reversed word into a trie. Following the reversed tail from the root leads to a single node, and every word whose insertion path passes through that node is a match.
Visiting all matches per query would be slow, so each trie node stores a best value: the best word, under the ranking rule, among all words passing through that node. The ranking is:
- the longer word wins;
- on equal length, the lexicographically smaller word wins.
While inserting a word, we update best at every node along its path using this comparison. A query then walks at most len(tail) edges and reads best from the final node. If an edge is missing along the way, no word has that tail, so we return "".
Operation names are checked as queries are processed. Any name other than "find_best_word" raises ValueError.
Why it is correct
- Matching set: the words passing through the node reached by
reverse(t)are exactly the words ending int. - Cached best is exact: the ranking is a total order on strings, so a running best at each node equals the maximum over precisely the words through it, regardless of insertion order.
- No match: a missing child edge means no word has that tail, so we return
""instead of reading the best of a partial path. A tail longer than every word also runs off the trie. - Duplicates: inserting the same word again compares equal and changes nothing.
- Empty dictionary: only the root exists, so the first step of every query fails and returns
"". - Empty tail: no edges are followed, so the root's best (the best word overall) is returned.
- Unknown operation: raises
ValueError.
Complexity
Let N be the total number of characters in all words and m the tail length.
- Build: O(N) node visits, each with a comparison. A length tie can make a string comparison cost more in adversarial cases, which can be avoided by pre-ranking the words once.
- Query: O(m).
- Space: O(N) trie nodes.
Reference solution
from typing import List
def longest_word_with_tail(words: List[str], operations: List[str], arguments: List[List[str]]) -> List[str]:
# Node 0 is the root; each node has child links and a cached best word.
trie = [{"children": {}, "best": ""}]
def better(current: str, candidate: str) -> str:
if not current:
return candidate
if len(candidate) > len(current):
return candidate
if len(candidate) == len(current) and candidate < current:
return candidate
return current
for word in words:
trie[0]["best"] = better(trie[0]["best"], word)
node = 0
for ch in reversed(word):
children = trie[node]["children"]
if ch not in children:
children[ch] = len(trie)
trie.append({"children": {}, "best": ""})
node = children[ch]
trie[node]["best"] = better(trie[node]["best"], word)
result = []
for operation, args in zip(operations, arguments):
if operation != "find_best_word":
raise ValueError(f"Unknown operation: {operation}")
tail = args[0]
node = 0
found = True
for ch in reversed(tail):
nxt = trie[node]["children"].get(ch)
if nxt is None:
found = False
break
node = nxt
result.append(trie[node]["best"] if found else "")
return result