Twitter Interview Question
InternsCountry: United States
1. Make a graph, from your string[] bank.
All strings become nodes.
A node is connected to another if they have a single edit distance, that is ,
a single mutation can transform one string to another. Thus, making the graph is hard affair.
Linear solution on the strings lengths exists, see below ZoomBA code.
2. Once that graph building is done, search for the node.
Keep a hashmap/trie whatever you want.
Get the start and end node. Now, apply any standard path finding mechanism to
reach from start to the end node, in the shortest path. The weight of the path is the mutation distance.
// ZoomBA
def is_edit_distance_1( string1, string2 ){
n1 = #|string1| ; n2 = #|string2|
if ( #|n1 - n2| > 1 ) return false
if ( n1 == n2 ) return test_same_length( string1, string2 )
if ( n1 > n2 ) return test_one_more ( string1 , string2 )
return test_one_more ( string2 , string2 )
}
def test_same_length( string1, string2 ){
n = #|string2|
( lfold ( [0:n] , 0 ) ->{
$.partial += (string1[$.o] == string2[$.o] ? 0 : 1 )
break ( $.partial > 1 )
$.partial
} ) == 1
}
def test_one_more( large, small ){
n = #|small|
first_diff = index( [0:n] ) :: {
small[ $.o ] != large[ $.o ]
}
if ( first_diff < 0 ) return true
// match the suffixes
! exists ( [ first_diff : n ] ) :: {
large[$.o+1] != small[$.o]
}
}
Are the sequences guaranteed to be of the same length?
- dunkmoomoo October 11, 2016