Ctrl K

Best Match by Ending

Hard
You are given a dictionary catalog and a list of queries queries. For each query queries[i], find the word in catalog that shares the longest common ending (suffix) with it. If several words tie, choose the shortest of them, and if the length ties too, the one that comes earlier in catalog. The common ending may be empty, in which case every catalog word competes. Return an array whose i-th element is the index in catalog of the word chosen for queries[i].
Example 1
catalog=["station", "nation", "ion"], queries=["motion", "nation", "cat"] → [1, 1, 2]

motion shares the ending tion with both station and nation; the shorter nation wins (index 1). nation matches nation completely (1). cat shares no ending with anything, so every word ties and the shortest, ion, wins (2).

Example 2
catalog=["dog", "log", "fog"], queries=["frog", "dg"] → [0, 0]

Every catalog word ties on both the shared ending and the length, so the earliest one, index 0, wins each time.

Constraints
  • 1 ≤ len(catalog), len(queries) ≤ 10⁴
  • 1 ≤ len(catalog[i]), len(queries[i]) ≤ 5000
  • The words in catalog have total length at most 5 · 10⁵, and so do the words in queries
  • All words consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardWords Hidden in a Letter Grid HardGlued Into a Palindrome HardMirror Word Blocks HardWords Built From Shorter Words Hard
loading Python…
Input
catalog=["station", "nation", "ion"], queries=["motion", "nation", "cat"]
Expected
[1, 1, 2]

Run checks the first 3 tests in your browser. Submit checks all 81 tests on the server, hidden ones included.