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
Longest Common Suffix QueriesContainer Wordsabababaabaindex 0index 1index 2Query WordabaSuffix Analysis:suffix: aba (3)suffix: ba (2)suffix: aba (3)length: 5length: 2length: 3Best: index 2 (same suffix length, shorter word)Output: [2]
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
Asked in
Google 25 Amazon 18 Microsoft 15
33.8K Views
Medium Frequency
~35 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