Given String p and list of strings find the shortest string for which p is the prefix.
I know the brute force approach but what will be the optimal approach?
e.g.
p = "foo bar"
list = {"foo bar 1",
"foo bar foo bar",
"bar foo foo foo bar bar"};
Should return “foo bar 1”
If you already have a search space (in your case, a relatively constant
list), then generating a trie or some other suitable structure would help searching a lot. Start with Wikipedia which explains this in enough detail to get you started:Here’s an image from the above article that uses words (which readily extends to using strings of any kind or even non-strings):
The article provides some performance comparisons with other suitable structures, which is helpful in your case.
Note that if list changes sufficiently enough, then the returns of this approach might diminish or you can even have worse performance compared to brute-force.