# Code golf edit distance 2

The edit distance between two strings is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other.

This task is simply to write code that determines if two strings have edit distance exactly 2 from each other. The twist is that your code must run in linear time. That is if the sum of the lengths of the two strings is n then your code should run in O(n) time.

# Example of strings with edit distance 2.

elephant elepanto
elephant elephapntv
elephant elephapntt
elephant lephapnt
elephant blemphant
elephant lmphant
elephant velepphant


# Examples where the edit distance is not 2. The last number in each row is the edit distance.

elephant elephant 0
elephant lephant 1
elephant leowan 4
elephant leowanb 4
elephant mleowanb 4
elephant leowanb 4
elephant leolanb 4
elephant lgeolanb 5
elephant lgeodanb 5
elephant lgeodawb 6
elephant mgeodawb 6
elephant mgeodawb 6
elephant mgeodawm 6
elephant mygeodawm 7
elephant myeodawm 6
elephant myeodapwm 7
elephant myeoapwm 7
elephant myoapwm 8


You can assume the input strings have only lower case ASCII letters (a-z).

Your code should output something Truthy if the edit distance is 2 and Falsey otherwise.

If you are not sure if your code is linear time, try timing it with pairs of strings of increasing length where the first is all 0s and the second string is one shorter with one of the 0s changed to a 1. These all have edit distance 2. This is not a good test of correctness of course but a quadratic time solution will timeout for strings of length 100,000 or more where a linear time solution should still be fast.

• You don't describe what linear time means here. I assume you mean the execution time should be linear in the length of the two inputs? If so, you should probably include a set of cases that would allow numerical testing to reduce the reliance on proving it. – FryAmTheEggman Apr 2 '20 at 20:25
• Given that the word size is $W$, would an $O(NW)$ solution be allowed? – dingledooper Apr 2 '20 at 20:49
• Uh, Anush, could you look at the list of your newest questions? I see far too many patterns there – the default. Apr 3 '20 at 2:38
• @mypronounismonicareinstate The average edit distance between Anush's challenge titles has gone down lately :P – xnor Apr 3 '20 at 3:56
• I am very glad to provide a service to fill in the terrible gap in edit distance questions which codegolf.se has had. When there are as many edit distance questions as quine questions my job will be done. – user9207 Apr 3 '20 at 10:05

3 bytes saved by Bubbler

x%y=2==(x#y)0
(u@(a:b)#v@(c:d))x|a==c=b#d$x|x<2=minimum$map($x+1)[d#u,b#v,b#d] ((a:b)#c)x=1+(b#c)x (c#[])x=x (a#b)x=b#a$x


Try it online!

This algorithm is a simple modification of a edit distance calculation except it checks that the edit distance is equal to 2 at the end and only branches if we have branched fewer than 2 times previously.

This algorithm is linear since it has a hard limit of 9 branches total, each of which traverses the input in linear time.

• Fails on input "abcd" "ebcd": expected False (because edit distance is 1), but got True. – Bubbler Apr 3 '20 at 1:12
• It still fails my test case. – Bubbler Apr 3 '20 at 1:36
• 121 – Bubbler Apr 3 '20 at 2:26
• I was trying to use Haskell's lazy evaluation to shortcut edit distance greater than 2, but it seems not to work: TIO. Not sure why. I thought that since, say, min[0,0][0,0..] short-circuits evaluation it's wouldn't evaluate branches with with results above [0,0] for distance 2. – xnor Apr 3 '20 at 3:39
• @Anush An empty Haskell program on TIO also seems to take about a second to run. – xnor Apr 3 '20 at 12:47

# Retina 0.8.2, 76 58 bytes

^(.*)(.*¶)\1
$2 (.*)(¶.*)\1$
$2 ^.?¶.?$

^.?(.*).?¶.?\1.?$ Try it online! Takes the two strings on separate lines, but link includes test suite which takes space-separated strings instead, so that I can easily use the test cases. Explanation: ^(.*)(.*¶)\1$2


Delete the common prefix.

(.*)(¶.*)\12


Delete the common suffix.

^.?¶.?$ Ignore an edit distance of less than two. ^.?(.*).?¶.?\1.?$


Check that only the first and last characters have been edited, so that the edit distance cannot be greater than two in this case.

From a code golf point of view this can be done in 51 bytes but then the regex becomes unbearably slow to execute for longer strings:

^(?!(.*).?(.*)¶\1.?\2$)(.*).?(.*).?(.*)¶\3.?\4.?\5$


Try it online! Takes the two strings on separate lines, but link includes test suite which takes space-separated strings instead, so that I can easily use the test cases. Explanation:

^


Match the whole input.

(?!(.*).?(.*)¶\1.?\2$)  Don't match strings with an edit distance less than two. (.*).?(.*).?(.*)¶\3.?\4.?\5$


Match strings with an edit distance less than three.

• This looks great but I am not sure what you have done. Take the strings abab and babz. They have no common prefix or suffix. What does your code do next? – user9207 Apr 2 '20 at 21:23
• @Anush It checks that the middles of the two strings are the same, but at least one of the strings must have its first character skipped and at least one of the strings must have its last character skipped. – Neil Apr 2 '20 at 21:44
• @Anush Actually I've tweaked the code slightly now so that it simply tests all permutations of removing leading and trailing characters from both strings to see whether the remainder matches. As this now matches any strings with an edit distance of less than three I've also had to tweak my rejection to include all edits with a distance of less than two. – Neil Apr 2 '20 at 21:51
• It's a very nice and simple solution to what could have been a hard question. It also runs fast! – user9207 Apr 3 '20 at 10:07
• @Anush Actually not quite as fast as it should... a one byte golf I made earlier makes the suffix removal really slow, so I've reverted that change. But if it's slow you want, I've got a 51 byte solution ;-) – Neil Apr 3 '20 at 10:28

# Python 3.8, 273 $$\\cdots\$$316 312 bytes

Added 30 bytes to fix bugs kindly pointed out by Bubbler.
Added 12 bytes to fix a bug kindly pointed out by ovs.
Saved 9 bytes thanks to ovs!!!

def f(*x,i=0):
b,a=w=sorted(x,key=len);d,c=map(len,w)
while a[i]==b[i]:
if(i:=i+1)==d:return i==c-2
while a[c-1]==b[d-1]:
if d==1:return c==3
c-=1;d-=1
a=a[i:c]
b=b[i:d]
return c-i>1and((x:=a[1:-1])==(y:=b[1:-1])or a[:-1]==y or a[1:]==y or a[:-1]==b[1:]or a[1:]==b[:-1]or x==b[:-1]or x==b[1:]or x==b)


Try it online!

• Fails on "abcd", "ad" with error. – Bubbler Apr 3 '20 at 6:12
• @Bubbler Yup, missed that case. Should be ok now. Thanks! :-) – Noodle9 Apr 3 '20 at 6:23
• Now fails on "abcd", "a"; should be false (edit distance 3). – Bubbler Apr 3 '20 at 6:25
• @Bubbler Was just fixing that. Thanks again! :-) – Noodle9 Apr 3 '20 at 6:28
• It really nice and fast now! Congratulations. Everyone please upvote. – user9207 Apr 4 '20 at 18:56