Longest Common Suffix Queries - Problem
You have two collections of words: a container of strings and a list of query strings. For each query word, your mission is to find the word in the container that shares the longest common suffix with it.
But here's where it gets interesting - if multiple words tie for the longest suffix match, you need to pick the shortest one. And if there's still a tie? Choose the one that appeared earliest in the container.
Example: If your query is "running" and your container has ["sing", "ring", "walking"], both "sing" and "ring" share the suffix "ing" (3 characters), but "sing" is shorter, so it wins!
Return an array of indices pointing to the best match for each query.
Input & Output
example_1.py โ Basic Suffix Matching
$
Input:
wordsContainer = ["abcd", "bcd", "xbcd"]
wordsQuery = ["cd"]
โบ
Output:
[1]
๐ก Note:
All three words end with "cd", but "bcd" is shortest (3 chars) so it wins. Query "cd" matches with container word at index 1.
example_2.py โ Tie Breaking by Length
$
Input:
wordsContainer = ["abcdefg", "ba", "cc", "dddd"]
wordsQuery = ["string", "a"]
โบ
Output:
[1, 1]
๐ก Note:
For "string": no common suffixes, so choose shortest word "ba" (index 1). For "a": "ba" ends with "a", so index 1 is returned.
example_3.py โ Multiple Queries
$
Input:
wordsContainer = ["word", "sword", "world"]
wordsQuery = ["ord", "ld", "orld"]
โบ
Output:
[0, 2, 2]
๐ก Note:
"ord": all words match "ord" suffix, "word" is shortest and earliest (index 0). "ld": only "world" matches (index 2). "orld": only "world" matches (index 2).
Constraints
- 1 โค wordsContainer.length, wordsQuery.length โค 104
- 1 โค wordsContainer[i].length โค 5 ร 103
- 1 โค wordsQuery[i].length โค 5 ร 103
- All strings consist of lowercase English letters only
- Sum of wordsContainer[i].length โค 5 ร 105
- Sum of wordsQuery[i].length โค 5 ร 105
Visualization
Tap to expand
Understanding the Visualization
1
Reverse Word Organization
Store all words backwards in a tree structure, like organizing phone numbers by their last digits
2
Track Best Matches
At each tree node, remember the shortest word that passes through it
3
Query Processing
For each query, walk the tree backwards to find the longest matching path
4
Retrieve Best Match
Return the stored best word from the deepest matching node
Key Takeaway
๐ฏ Key Insight: A suffix trie organized by word endings allows us to find the longest common suffix in O(M) time per query, rather than comparing against all N words each time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code