Java DP solution - O(nm)
Let following be the function definition :-\n\nf(i, j) := minimum cost (or steps) required to convert first i characters of word1 to first j characters of word2
Let following be the function definition :-\n\nf(i, j) := minimum cost (or steps) required to convert first i characters of word1 to first j characters of word2\n\nCase 1: word1[i] == word2[j], i.e. the ith the jth character matches.\n\n> f(i, j) = f(i - 1, j - 1)\n\nCase 2: word1[i] != word2[j], then we must either insert, delete or replace, whichever is cheaper\n\n> f(i, j) = 1 + min { f(i, j - 1), f(i - 1, j), f(i - 1, j - 1) }\n\n1. f(i, j - 1) represents insert operation\n2. f(i - 1, j) represents delete operation\n3. f(i - 1, j - 1) represents replace operation\n\nHere, we consider any operation from word1 to word2. It means, when we say insert operation, we insert a new character after word1 that matches the jth character of word2. So, now have to match i characters of word1 to j - 1 characters of word2. Same goes for other 2 operations as well.\n\nNote that the problem is symmetric. The insert operation in one direction (i.e. from word1 to word2) is same as delete operation in other. So, we could choose any direction.\n\nAbove equations become the recursive definitions for DP.\n\nBase Case: \n\n> f(0, k) = f(k, 0) = k\n\nBelow is the direct bottom-up translation of this recurrent relation. It is only important to take care of 0-based index with actual code :-\n\n    public class Solution {\n        public int minDistance(String word1, String word2) {\n            int m = word1.length();\n            int n = word2.length();\n            \n            int[][] cost = new int[m + 1][n + 1];\n            for(int i = 0; i <= m; i++)\n                cost[i][0] = i;\n            for(int i = 1; i <= n; i++)\n                cost[0][i] = i;\n            \n            for(int i = 0; i < m; i++) {\n                for(int j = 0; j < n; j++) {\n                    if(word1.charAt(i) == word2.charAt(j))\n                        cost[i + 1][j + 1] = cost[i][j];\n                    else {\n                        int a = cost[i][j];\n                        int b = cost[i][j + 1];\n                        int c = cost[i + 1][j];\n                        cost[i + 1][j + 1] = a < b ? (a < c ? a : c) : (b < c ? b : c);\n                        cost[i + 1][j + 1]++;\n                    }\n                }\n            }\n            return cost[m][n];\n        }\n    }\n\nTime complexity : If n is the length of word1, m of word2, because of the two indented loops, it is O(nm)
['Dynamic Programming', 'Java']