-3

How is a trie useful if one has to at least read all the characters from the input array of strings to insert the strings one by one into the trie? So the complexity is O(size_of_array). Suppose the input array of strings is {"hello",world","stack","overflow"}, and we want to search for "stack", then we would have to at least traverse the whole array for inserting the keys into the trie. So complexity is O(size_of_array). We could do this without a trie.

OmG
  • 18,337
  • 10
  • 57
  • 90

1 Answers1

0

The point of a trie is for many queries.

  • A trie offers a relatively cheap insertion of each string.
  • A trie offers a relatively cheap search for a string.

That means, if you have an array, and you need to query existence of a string in it just once - it will probably not be very helpful, since creation of the trie for a single query is wasteful.

However, if you have a dictionary, and you are going to query it next millions of time - it is significantly more efficient to search the trie, than to repeatedly search the array - and that's where you benefit from it.

Brien Foss
  • 3,336
  • 3
  • 21
  • 31
amit
  • 175,853
  • 27
  • 231
  • 333
  • @amit From my experience, that is not quite the case in practice (it's a *very* slow data structure to use as a dictionary). It makes a good auto-completer, though, and has some other (limited applicability) uses. – Ami Tavory Jun 27 '15 at 09:11
  • @AmiTavory The question asks about asymptotic complexity (using big O notation in the question), so I explained why (and when) in these terms trie is preferable over array. Also, I deliberately used the *relatively* in the answer - to amphisize I am comparing to the array alternative. – amit Jun 27 '15 at 12:58