codekofi
← All problems

Problem 44

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1int solution(const string& a, const string& b) {
2
3 int m = a.size();
4 int n = b.size();
5
6 vector<int> prev(n + 1, 0);
7 vector<int> curr(n + 1, 0);
8
9 for (int j = 0; j <= n; j++) {
10 prev[j] = j;
11 }
12
13 for (int i = 1; i <= m; i++) {
14
15 curr[0] = i;
16
17 for (int j = 1; j <= n; j++) {
18
19 if (a[i - 1] == b[j - 1]) {
20 curr[j] = prev[j - 1];
21 continue;
22 }
23
24 int replace = prev[j - 1];
25 int remove = prev[j];
26 int insert = curr[j - 1];
27
28 curr[j] = 1 + min(replace, min(remove, insert));
29 }
30
31 swap(prev, curr);
32 }
33
34 return prev[n];
35}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.