Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if edit distance between two strings is one in Python
The edit distance between two strings represents the minimum number of operations needed to transform one string into another. To check if the edit distance is exactly one, we need to verify that only a single operation is required. The three possible operations are ?
- Insert a character
- Delete a character
- Replace a character
For example, if s = "hello" and t = "heillo", we need to insert one character 'i' into s to get t, so the edit distance is 1.
Algorithm
The approach uses a two-pointer technique to traverse both strings simultaneously ?
- If the length difference is greater than 1, return False (impossible with one edit)
- Use two pointers to compare characters
- When characters differ, handle based on string lengths
- Count the total edit operations needed
Implementation
def solve(s, t):
if abs(len(s) - len(t)) > 1:
return False
edit_dist_cnt = 0
i = 0
j = 0
while i < len(s) and j < len(t):
if s[i] != t[j]:
if edit_dist_cnt == 1:
return False
if len(s) > len(t):
i += 1 # Delete from s
elif len(s) < len(t):
j += 1 # Insert into s
else:
i += 1 # Replace operation
j += 1
edit_dist_cnt += 1
else:
i += 1
j += 1
# Handle remaining characters
if i < len(s) or j < len(t):
edit_dist_cnt += 1
return edit_dist_cnt == 1
# Test the function
s = "hello"
t = "heillo"
print(solve(s, t))
True
How It Works
Let's trace through the example with s = "hello" and t = "heillo" ?
def solve_with_trace(s, t):
print(f"Comparing '{s}' and '{t}'")
if abs(len(s) - len(t)) > 1:
print("Length difference > 1, returning False")
return False
edit_dist_cnt = 0
i = 0
j = 0
while i < len(s) and j < len(t):
print(f"Comparing s[{i}]='{s[i]}' with t[{j}]='{t[j]}'")
if s[i] != t[j]:
print(f"Characters differ! Edit count: {edit_dist_cnt + 1}")
if edit_dist_cnt == 1:
return False
if len(s) < len(t):
j += 1 # Insert into s
print(f"Insert operation: moving j to {j}")
edit_dist_cnt += 1
else:
print("Characters match")
i += 1
j += 1
if i < len(s) or j < len(t):
edit_dist_cnt += 1
print(f"Remaining characters, final edit count: {edit_dist_cnt}")
return edit_dist_cnt == 1
# Test with detailed trace
s = "hello"
t = "heillo"
result = solve_with_trace(s, t)
print(f"Result: {result}")
Comparing 'hello' and 'heillo' Comparing s[0]='h' with t[0]='h' Characters match Comparing s[1]='e' with t[1]='e' Characters match Comparing s[2]='l' with t[2]='i' Characters differ! Edit count: 1 Insert operation: moving j to 3 Comparing s[2]='l' with t[3]='l' Characters match Comparing s[3]='l' with t[4]='l' Characters match Comparing s[4]='o' with t[5]='o' Characters match Result: True
Multiple Test Cases
def test_edit_distance():
test_cases = [
("hello", "heillo", True), # Insert 'i'
("cat", "bat", True), # Replace 'c' with 'b'
("abc", "ab", True), # Delete 'c'
("abc", "xyz", False), # Multiple replacements needed
("", "a", True), # Insert into empty string
("same", "same", False), # No edits needed
("ab", "abcd", False), # Need 2 insertions
]
for s, t, expected in test_cases:
result = solve(s, t)
status = "?" if result == expected else "?"
print(f"{status} '{s}' ? '{t}': {result} (expected {expected})")
test_edit_distance()
? 'hello' ? 'heillo': True (expected True) ? 'cat' ? 'bat': True (expected True) ? 'abc' ? 'ab': True (expected True) ? 'abc' ? 'xyz': False (expected False) ? '' ? 'a': True (expected True) ? 'same' ? 'same': False (expected False) ? 'ab' ? 'abcd': False (expected False)
Conclusion
This algorithm efficiently checks if two strings have an edit distance of exactly one using a two-pointer approach. It handles all three edit operations (insert, delete, replace) and runs in O(min(m,n)) time complexity where m and n are the string lengths.
