Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to transform one word to another through valid words

I came across this variation of edit-distance problem:

Design an algorithm which transforms a source word to a target word. for example: from head to tail, in each step, you just can replace one character, and the word must be valid. You'll be given a dictionary.

It clearly is a variation of the edit distance problem, but in edit distance I do not care about if the word is valid or not. So how do I add this requirement to edit distance.

like image 765
gameover Avatar asked Feb 05 '10 07:02

gameover


1 Answers

This can be modelled as a graph problem. You can think of the words as nodes of the graph and two nodes are connected if and only if they are of same length and differ in one char.

You can preprocess the dictionary and create this graph, should look like:

   stack  jack     |      |     |      |    smack  back -- pack -- pick 

You can then have a mapping from the word to the node representing the word, for this you can use a hash table, height balanced BST ...

Once you have the above mapping in place, all you have to do is see if there exists a path between the two graph nodes, which can easily be done using BFS or DFS.

So you can summarize the algorithm as:

preprocess the dictionary and create the graph. Given the two inputs words w1 and w2 if length(w1) != length(w2)  Not possible to convert else  n1 = get_node(w1)  n2 = get_node(w2)   if(path_exists(n1,n2))    Possible and nodes in the path represent intermediary words  else    Not possible 
like image 114
codaddict Avatar answered Oct 31 '22 13:10

codaddict