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.