0

How can we solve this problem in a best way? Is there any algorithm for solving this? "In a paragraph we have to find and print all the words which have starting 3 letters same. Example: we input some paragraph and as a output we get letters like-

a) 1. you 2. your 3. yours 4. yourself

b) 1. early 2. earlier 3. earliest

Like this we get all the words of paragraph which have starting 3 letters common"

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065

2 Answers2

0

A reasonable solution that's not too hard to code up is to maintain a map of some sort where the keys are the first three letters of each word and the values are the sets of words that start with those three letters. You can scan across the words in the paragraph and, for each one you encounter, trim off the first three words, look up the map entry corresponding to those letters, and add in that word to the list. You can then iterate over the map at the end, find all sets containing at least two words, then print out each cluster you find.

Overall, the runtime of this approach is O(L), where L is the total length of all the words in the paragraph. To see this, notice that for each word, we do a map lookup on a constant-sized prefix of that word, then copy all the characters of the word into the map. Overall, this visits each character at most a constant number of times.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

Trie with the first three characters and then the word index as the leaf should do the trick.

Prathik Rajendran M
  • 1,152
  • 8
  • 21