-1

So I got this question in an interview recently:

Given a dictionary and a starting string, what is the longest word you can form by adding one character at a time to the front and back of input string, with every new word must also appear in the dictionary?

Ex: input = 'at' Dict = {hat, chat, chats, rat, tat, tats, chatats}

Return 'chats', because: at -> hat -> chat -> chats

I thought of a solution where we bruteforce and try adding all letters from a - z to both front and back of the input string, and if new string exists then we bruteforce the 26 letters to front and back again to eventually get the final string.

I was wondering if there's a more efficient method to solving this problem without brute forcing all 26 letters to front and back every time?

One approach I thought of was going through the dictionary and if input string exists as a substring for any entry that has a length greater by 1 than the lenght of changing input string, then delete the input substring from the entry string.

Ex: after 1st iteration, dict would be = {h, chat, chats, r, t, tats, chatats}

And we would also have a length variable for each entry keep track of the original length of the entry. But I'm not exactly sure if this is a correct approach/would even work.

1 Answers1

1

Build a graph of words and their shorter/longer versions, e.g. for the word list in the question (hat, chat, chats, rat, tat, tats, chatats), that would be:

                           chatats
hat ─── chat ─── chats
rat
tat ─── tats

Build the graph backwards, i.e. for every word, look for the 2 shorter words by removing either the leading or the trailing character.

For faster lookup, build a Map of words to their graph node.

Now find the longest chain in the graph.

Andreas
  • 154,647
  • 11
  • 152
  • 247