To determine whether two strings are similar based on the Levenshtein edit distance not exceeding a certain threshold ( k ), we can use a dynamic programming approach optimized for the given constraints.
Here's a step-by-step solution:
-
Handle the Length Difference Early:
- If the difference in lengths of the two strings exceeds ( k ), we can immediately conclude that the strings are not similar, output "No", and proceed to the next test case. This is because the minimum edit distance would be at least the difference in lengths.
-
Optimized Dynamic Programming with Banded Matrix:
- Since ( k ) is small (up to 20), we can optimize the dynamic programming matrix to only consider cells where the absolute difference of indices ( |i - j| \leq k ).
- This reduces the time complexity from ( O(N \times M) ) to ( O(k \times (N + M)) ), where ( N ) and ( M ) are the lengths of the two strings.
-
Initialize DP Arrays:
- Use two arrays,
prev_row and current_row, of size up to ( 2k + 1 ) to store the DP values for the previous and current rows, respectively.
- Adjust the indices to account for the starting index ( start_j = \max(0, i - k) ).
-
Fill the DP Arrays:
- Loop through each character in the first string.
- For each position, compute the values in the
current_row for indices within the bandwidth ( [\max(0, i - k), \min(M, i + k)] ).
- The recurrence relation is:
[
\text{dp}[i][j] = \begin{cases}
\text{dp}[i - 1][j - 1], & \text{if } \text{s}[i - 1] = \text{t}[j - 1] \
1 + \min(\text{dp}[i - 1][j], \text{dp}[i][j - 1], \text{dp}[i - 1][j - 1]), & \text{otherwise}
\end{cases}
]
-
Check the Result:
- After processing, if the final edit distance (the last element in
current_row) is less than or equal to ( k ), output "Yes". Otherwise, output "No".
-
Repeat for All Test Cases:
- Process each test case individually using the above steps.
Now, here's the implementation code:
t = int(input())
for _ in range(t):
k = int(input())
s = input()
t_str = input()
n = len(s)
m = len(t_str)
if abs(n - m) > k:
print("No")
continue
# Initialize previous and current rows
prev_row = None
current_row = None
# We only need to keep the last two rows of the DP table
prev_row = [j if j <= k else k+1 for j in range(m+1)]
for i in range(1, n+1):
current_row = [0]*(m+1)
current_row[0] = i if i <= k else k+1
# Set the band boundaries
start = max(1, i - k)
end = min(m, i + k)
for j in range(start, end+1):
if s[i-1] == t_str[j-1]:
cost = 0
else:
cost = 1
current_row[j] = min(prev_row[j]+1, current_row[j-1]+1, prev_row[j-1]+cost)
prev_row, current_row = current_row, prev_row
# If the edit distance is within k, output Yes, else No
if prev_row[m] <= k:
print("Yes")
else:
print("No")