Given this problem formulation and the official solution in the code block:
Given an array of n integers A and an array of m integers B such that n <= m. What is the minimum number of elements of B that you need to replace by other integers so that A is a subsequence of B? (not necessarily on consecutive indices)
For example, for A = [1, 5, 2, 3] and B = [1, 4, 2, 5, 6, 2, 5], the answer is 1, and it is obtained by replacing the last element of B by 3. Also, for A = [1, 5, 2, 3] and B = [5, 8, 8, 2, 8, 8, 3], the answer is 2, and it is obtained by replacing the first two elements of B by 1 and 5.
Your solution needs to run in O(n*m) time.
public static int editToSubsequence(int n, int m, int[] A, int[] B) {
// IDEA: Dynamic programming DP[i][j] = minimum number of edits such that
// indices 0...i-1 of A are a subsequence of indices 0...j-1 of B.
// We set DP[i][j] = n + 1 for j < i, because that case is impossible.
// Otherwise, the main recursion is:
// - if A[i - 1] = B[j - 1], we can set DP[i][j] = DP[i - 1][j - 1]
// - else, we can set DP[i][j] = DP[i - 1][j - 1] if we edit B[j],
// or DP[i][j] = DP[i][j - 1] if we do not use B[j]
int[][] DP = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
DP[i][j] = n + 1;
}
}
for (int i = 1; i <= n; i++) {
for (int j = i; j <= m; j++) {
if (A[i - 1] == B[j - 1]) {
DP[i][j] = DP[i - 1][j - 1];
} else {
DP[i][j] = Math.min(DP[i][j - 1], DP[i - 1][j - 1] + 1);
}
}
}
return DP[n][m];
}
Can someone explain where the intuition for this appraoch should come from? I am familiar with both Longest Common Subsequence and Minimal Edit Distance in DP, but this is not an obvious approach to me.
CharComplexity is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.