Skip to main content

Prefix and Suffix Search

HardHash TableStringDesignTrie

Description

Given words, find the word with given prefix and suffix. Return the index of the word with largest index.

Examples

Input:words = ["apple"], prefix = "a", suffix = "e"
Output:0
Explanation:

'apple' has prefix 'a' and suffix 'e'.

Input:words = ["banana", "band", "bandana", "can"], prefix = "ban", suffix = "a"
Output:2
Explanation:

Both 'banana' (index 0) and 'bandana' (index 2) have prefix 'ban' and suffix 'a'. The word with the largest index is returned, so the answer is 2 for 'bandana'.

Input:words = ["test", "testing", "best", "rest"], prefix = "te", suffix = "ng"
Output:1
Explanation:

Only 'testing' (index 1) has prefix 'te' and suffix 'ng'. The other words either don't start with 'te' or don't end with 'ng'.

Constraints

  • 1 ≤ words.length ≤ 10⁴

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.