Skip to content

Practice Prefix and Suffix Search

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#745
LeetCode Problem

Prefix and Suffix Search

Problem Statement

WordFilter(words) stores words with their original zero-based indices. f(pref,suff) returns the largest index whose word starts with pref and ends with suff, or -1 when none matches. Prefix and suffix may overlap inside the word. Practice approach: Precompute a map from each prefix/suffix pair to the largest matching index. Short words make this bounded O(nL^2) pair enumeration practical. Process words in increasing index order so later entries replace earlier ones. A trie over combined suffix and prefix keys is another approach. Test repeated words and overlapping matches.

Source: Prefix and Suffix Search on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["WordFilter","f","f","f"]
[[["cat","car","cart"]],["ca","t"],["car","r"],["z","t"]]
Output
[null,2,1,-1]
Explanation

Both cat and cart match ca/t; cart has the larger index. car matches the overlapping prefix car and suffix r.

Constraints

1 <= words.length <= 10^4
1 <= word, prefix, suffix lengths <= 7
All strings contain lowercase letters.
At most 10^4 f calls.

Related LeetCode Problems

Practice more problems similar to Prefix and Suffix Search.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.