An edit between two strings is one of the following changes.
- Add a character
- Delete a character
- Change a character
Given two string s1 and s2, find if s1 can be converted to s2 with exactly one edit. Expected time complexity is O(m+n) where m and n are lengths of two strings.
Input: s1 = "geeks", s2 = "geek" Output: yes Number of edits is 1 Input: s1 = "geeks", s2 = "geeks" Output: no Number of edits is 0 Input: s1 = "geaks", s2 = "geeks" Output: yes Number of edits is 1 Input: s1 = "peaks", s2 = "geeks" Output: no Number of edits is 2
A Simple Solution is to find Edit Distance using Dynamic programming. If distance is 1, then return true, else return false. Time complexity of this solution is O(n2)
An Efficient Solution is to simultaneously traverse both strings and keep track of count of different characters. Below is complete algorithm.
Let the input strings be s1 and s2 and lengths of input strings be m and n respectively. 1) If difference between m an n is more than 1, return false. 2) Initialize count of edits as 0. 3) Start traversing both strings from first character. a) If current characters don't match, then (i) Increment count of edits (ii) If count becomes more than 1, return false (iii) If length of one string is more, then only possible edit is to remove a character. Therefore, move ahead in larger string. (iv) If length is same, then only possible edit is to change a character. Therefore, move ahead in both strings. b) Else, move ahead in both strings.
Below is the implementation of the above idea :
Time complexity: O(n)
Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting above solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Edit Distance | DP using Memoization
- Edit distance and LCS (Longest Common Subsequence)
- Check whether Strings are k distance apart or not
- Hamming Distance between two strings
- Meta Strings (Check if two strings can become same after a swap in one string)
- Check whether two strings are anagram of each other
- Check if two strings are permutation of each other
- Check if two given strings are isomorphic to each other
- Check if strings are rotations of each other or not | Set 2
- Check if two strings are k-anagrams or not
- Program to check if two strings are same or not
- Check if all the palindromic sub-strings are of odd length
- Check if there is any common character in two given strings
- Check whether two strings are equivalent or not according to given condition
- Check whether two strings contain same characters in same order