Algorithms – How to Search for a Sub-string in an Array of Strings

algorithmssearchstrings

I have an array of n strings. I want to select all the elements of the array that starts with the given string.

Sorry if that is not clear. I'll give an example.

input = "as"
array = ["abas", "aras", "as", "ask", "asi", "aso", "atas" ]
output =            ["as", "ask", "asi", "aso"]

Which algorithm will I need to do this selection. I need the fastest algorithm that will perform this operation since I'm using it for autoComplete in JavaScript. So the search should be faster than the typing speed of the user.

Edit: Was just thinking about the data I have to pre-process if using a data structure. The data would be dynamic, and I have to perform insert operation that many number of times. I'm fetching data dynamically using AJAX requests.

Edit 2: The array might contain 1 million entries and the search should be made at two places. One on the server side, to select all elements matching the condition. This can be restricted to 10000 entries, and the other on the client side… search size will be those 10000 entries, and this can be restricted to first 250 entries.

Sorry for the late editing of the question.

Best Answer

As a pre-processing step turn your list into a trie.

a trie, also called digital tree or prefix tree, is an ordered tree data structure that is used to store a dynamic set or associative array where the keys are usually strings. Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. Values are normally not associated with every node, only with leaves and some inner nodes that correspond to keys of interest...

The term trie comes from re-trie-val...

http://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Trie_example.svg/250px-Trie_example.svg.png

Related Topic