|
| 1 | +""" |
| 2 | +Question: |
| 3 | +One Away: There are three types of edits that can be performed on |
| 4 | +strings: insert a character, remove a character, or replace a |
| 5 | +character. Given two strings, write a function to check if they |
| 6 | +are one edit (or zero edits) away. |
| 7 | +
|
| 8 | +Example: |
| 9 | +pale, ple -> true |
| 10 | +pales, pale -> true |
| 11 | +pale, bale -> true |
| 12 | +pale, bake -> false |
| 13 | +
|
| 14 | +Source: Cracking the Code Interview 6th Edition Question 1.5 |
| 15 | +
|
| 16 | +Time Complexity: |
| 17 | +We are going through both strings at the same time and stopping when |
| 18 | +more than one letter is different, which means O(n) time complexity |
| 19 | +on the while loop. No extra space is required. |
| 20 | +""" |
| 21 | + |
| 22 | +def is_one_away(str1, str2): |
| 23 | + edit_counter = 0 |
| 24 | + i = 0 # str1 index |
| 25 | + j = 0 # str2 index |
| 26 | + |
| 27 | + # Size difference must be less than 1 |
| 28 | + if abs(len(str1) - len(str2)) > 1: |
| 29 | + return False |
| 30 | + |
| 31 | + # Compare strings while counting edits |
| 32 | + # If letters differ, update counter and compare next letter |
| 33 | + # In this case, if strings have different sizes increment only index of the longest |
| 34 | + # Otherwise increment both indexes |
| 35 | + while i < len(str1) and j < len(str2): |
| 36 | + if str1[i] != str2[j]: |
| 37 | + # Only one edit is allowed |
| 38 | + if edit_counter > 0: |
| 39 | + return False |
| 40 | + edit_counter += 1 |
| 41 | + |
| 42 | + if len(str1) > len(str2): |
| 43 | + i += 1 |
| 44 | + continue |
| 45 | + elif len(str1) < len(str2): |
| 46 | + j += 1 |
| 47 | + continue |
| 48 | + i += 1 |
| 49 | + j += 1 |
| 50 | + |
| 51 | + # If one string finished before the other, we will certainly |
| 52 | + # have one more edit to consider (adding the last letter), so |
| 53 | + # we must check if the edit counter is still empty |
| 54 | + if (i < len(str1) or j < len(str2)) and edit_counter > 0: |
| 55 | + return False |
| 56 | + |
| 57 | + return True |
| 58 | + |
| 59 | +# Driver code |
| 60 | +str1 = input("Enter first string: ") |
| 61 | +str2 = input("Enter second string: ") |
| 62 | +print(is_one_away(str1, str2)) |
0 commit comments