Longest Common Suffix Queries - Problem
You are given two arrays of strings wordsContainer and wordsQuery. For each wordsQuery[i], you need to find a string from wordsContainer that has the longest common suffix with wordsQuery[i].
If there are two or more strings in wordsContainer that share the longest common suffix, find the string that is the smallest in length. If there are two or more such strings that have the same smallest length, find the one that occurred earlier in wordsContainer.
Return an array of integers ans, where ans[i] is the index of the string in wordsContainer that has the longest common suffix with wordsQuery[i].
Input & Output
Example 1 — Basic Case
$
Input:
wordsContainer = ["ababa","ba","aba"], wordsQuery = ["aba"]
›
Output:
[2]
💡 Note:
Query 'aba' has longest common suffix 'aba' with wordsContainer[0] and wordsContainer[2]. Since wordsContainer[2] is shorter (length 3 vs 5), return index 2.
Example 2 — Earlier Index Priority
$
Input:
wordsContainer = ["abc","bcd","def"], wordsQuery = ["xyz"]
›
Output:
[0]
💡 Note:
Query 'xyz' has no common suffix with any container word (all return suffix length 0). Since all have same suffix length, choose the earliest index 0.
Example 3 — Multiple Queries
$
Input:
wordsContainer = ["a","aa","aaa"], wordsQuery = ["aa","a"]
›
Output:
[0,0]
💡 Note:
Query 'aa': suffix 'a' matches all, choose shortest word at index 0. Query 'a': suffix 'a' matches all, choose shortest word at index 0.
Constraints
- 1 ≤ wordsContainer.length, wordsQuery.length ≤ 104
- 1 ≤ wordsContainer[i].length ≤ 5 × 103
- 1 ≤ wordsQuery[i].length ≤ 5 × 103
- wordsContainer[i] consists only of lowercase English letters
- wordsQuery[i] consists only of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Container words and query words
2
Process
Find longest common suffix with priority rules
3
Output
Index of best matching container word for each query
Key Takeaway
🎯 Key Insight: Build suffix trie to efficiently find longest common suffixes with O(k) query time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code