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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With