Leetcode 161. One Edit Distance

Problem Explanation

We are given two strings s and t and the goal is to determine if they are "one edit distance" apart. They can be one edit distance apart in one of the following ways:

  1. We can insert a character into string s to get string t.
  2. We can remove a character from string s to get string t.
  3. We can replace a character in string s to get string t.

Let's take the example of s = '1203' and t = '1213'. Here, we can see that by replacing '0' in s with '1', we get the string t. So these strings are one edit distance apart and the output would be true.

Approach of the Solution

The solution provided takes an approach where it first checks if the length of string s is greater than string t and if it is, it flips the strings. That way we ensure that the string s is always less than or equal to string t in size.

Then, it loops through each character of both strings simultaneously, checking if the characters at the current index are equal. If they are not, it checks two conditions - if the lengths of both strings are equal, it checks if the remaining substring of both strings (from next index till end) are equal (which would mean that the current characters can be replaced to make strings equal). If the lengths are not equal, it checks if the remaining substring of s is equal to remaining substring from next index of t (which means we can delete the current character from t to get s).

Finally, if all characters are equal, then it checks if the length of string t is one more than the length of string s. If it is, it means we can delete the last character from t to get s, making them one edit distance apart.

Python Solution

1
2Python
3class Solution:
4    def isOneEditDistance(self, s: str, t: str) -> bool:
5        if len(s) > len(t):
6            s, t = t, s
7
8        for i in range(len(s)):
9            if s[i] != t[i]:
10                if len(s) == len(t):
11                    return s[i+1:] == t[i+1:]  # Replace current character
12                else:
13                    return s[i:] == t[i+1:]  # Delete current character
14
15        return len(s) + 1 == len(t)

Java Solution

1
2Java
3public class Solution {
4    public boolean isOneEditDistance(String s, String t) {
5        if (s.length() > t.length())
6            return isOneEditDistance(t, s);
7
8        for (int i = 0; i < s.length(); ++i) {
9            if (s.charAt(i) != t.charAt(i)) {
10                if (s.length() == t.length())
11                    return s.substring(i + 1).equals(t.substring(i + 1));  // Replace current character
12                else
13                    return s.substring(i).equals(t.substring(i + 1));  // Delete current character
14            }
15        }
16
17        return s.length() + 1 == t.length();
18    }
19}

Javascript Solution

1
2Javascript
3var isOneEditDistance = function(s, t) {
4    if (s.length > t.length)
5        return isOneEditDistance(t, s);
6
7    for (var i = 0; i < s.length; ++i) {
8        if (s.charAt(i) != t.charAt(i)) {
9            if (s.length == t.length)
10                return s.slice(i + 1) == t.slice(i + 1);  // Replace current character
11            else
12                return s.slice(i) == t.slice(i + 1);  // Delete current character
13        }
14    }
15
16    return s.length + 1 == t.length;
17};

C++ Solution

1
2C++
3class Solution {
4public:
5    bool isOneEditDistance(string s, string t) {
6        if (s.size() > t.size())
7            return isOneEditDistance(t, s);
8
9        for (int i = 0; i < s.size(); ++i) {
10            if (s[i] != t[i]) {
11                if (s.size() == t.size())
12                    return s.substr(i + 1) == t.substr(i + 1);  // Replace current character
13                else
14                    return s.substr(i) == t.substr(i + 1);  // Delete current character
15            }
16        }
17
18        return s.size() + 1 == t.size();
19    }
20};

C# Solution

1
2Csharp
3public class Solution {
4    public bool IsOneEditDistance(string s, string t) {
5        if (s.Length > t.Length)
6            return IsOneEditDistance(t, s);
7
8        for (int i = 0; i < s.Length; ++i) {
9            if (s[i] != t[i]) {
10                if (s.Length == t.Length)
11                    return s.Substring(i + 1) == t.Substring(i + 1);  // Replace current character
12                else
13                    return s.Substring(i) == t.Substring(i + 1);  // Delete current character
14            }
15        }
16
17        return s.Length + 1 == t.Length;
18    }
19}

In all above solutions, we are keeping track of the character at the current index in both strings. Depending upon whether the lengths of the strings are equal or not, we perform the replacement or deletion operation accordingly. If all the characters are same, we check if the length of t is one more than the length of s, and return the boolean value accordingly.# Time Complexity

The time complexity for all of the above solutions is O(n), where n is the length of the smaller string. This is because we iterate through the strings comparing the characters until an unequal character is found. In the case of all characters being equal, we iterate over the entire length of the string.

The reason for O(n) complexity is that although string slicing, substring or substr operations return a new string and may lead one to think that they must be O(n) operations, they are actually implemented in an efficient manner in most modern programming languages like Python, Java and Javascript. They return a new view of the existing string, which doesn't involve copying the string data, and is therefore an O(1) operation. This operation results in a constant-time complexity rather than a linear one.

Space Complexity

The space complexity is also O(1) for all the solutions, because we only use a constant amount of space to store the strings s and t and some other miscellaneous variables. There is no space usage that scales with the size of the input.

In some languages, the space complexity may appear to be O(n) due to the use of string slicing or substring, which can create new strings. However, as previously mentioned, these operations usually return a new view on the existing string data without actually copying it, hence not affecting the space complexity.

Conclusion

In conclusion, the above solutions execute efficiently with a time complexity of O(n) and space complexity of O(1). They demonstrate the different ways to check whether two strings are "one edit distance" apart, by performing just one operation of either character insertion, removal or replacement. These solutions are presented in multiple popular programming languages including Python, Java, JavaScript, C++, and C# to cater for different programming preferences.


Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ