4. Identify the bug in this Levenshtein distance C# code snippet:
int LevenshteinDistance(string a, string b) { int[,] dp = new int[a.Length, b.Length]; for (int i = 0; i < a.Length; i++) dp[i, 0] = i; for (int j = 0; j < b.Length; j++) dp[0, j] = j; for (int i = 1; i < a.Length; i++) { for (int j = 1; j < b.Length; j++) { int cost = (a[i] == b[j]) ? 0 : 1; dp[i, j] = Math.Min(Math.Min(dp[i - 1, j] + 1, dp[i, j - 1] + 1), dp[i - 1, j - 1] + cost); } } return dp[a.Length - 1, b.Length - 1]; }
medium
A. Array size should be (a.Length+1, b.Length+1) and loops adjusted
B. Cost calculation should use a[i-1] and b[j-1]
C. Return statement should be dp[a.Length, b.Length]
D. No bug, code is correct
Solution
Step 1: Check array size and indexing
dp array must be sized (a.Length+1, b.Length+1) to include empty prefixes; current size misses last row/column.
Step 2: Adjust loops to run from 0 to length inclusive
Loops should run to <= length to fill dp correctly; current loops miss last indices.
Final Answer:
Array size should be (a.Length+1, b.Length+1) and loops adjusted -> Option A
Quick Check:
dp array size must include empty string row/column [OK]
Hint: dp array must be one larger than string lengths [OK]
Common Mistakes:
Using array size equal to string length only
Incorrect loop bounds causing index errors
Ignoring empty string base cases
5. Given two strings s1 = "intention" and s2 = "execution", what is the Levenshtein distance between them? Use the standard operations: insert, delete, substitute.
hard
A. 5
B. 6
C. 4
D. 7
Solution
Step 1: Analyze differences between "intention" and "execution"
Compare characters and count minimal edits: substitutions and insertions/deletions.
Step 2: Calculate minimal edits manually
Edits: i->e (substitution), n->x (substitution), t->c (substitution), insert u, substitute n->o, substitute n->n (no change), total 5 edits.
Final Answer:
5 -> Option A
Quick Check:
Distance("intention", "execution") = 5 [OK]
Hint: Count substitutions and insertions carefully [OK]
Common Mistakes:
Underestimating substitutions needed
Ignoring insertions or deletions
Confusing with Hamming distance
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.