1.
BruteForce, check all pairs and verify if they differ in one character.
O(n^2 * m) where n is the number of words and m is the length of each string.
classSolution {publicbooleandifferByOne(String[] dict) {int n =dict.length;for (int i =0; i < n ;i++) {for (int j = i+1; j < n; j++) {int count =0;for (int w =0 ; w < dict[i].length(); w++) {if (dict[i].charAt(w) != dict[j].charAt(w)) { count++; } }if (count ==1) {returntrue; } } }returnfalse; }}
2.use hashset
2.
T: O(m^2 * n), Use hashset,
to insert all possible combinations adding a character "*".
For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
1 word, len m => generated m string, so m^2
n word => so n*m^2
S: O(m^2 * n)
classSolution {publicbooleandifferByOne(String[] dict) {Set<String> seen =newHashSet<>();for (String w : dict) {char[] c =w.toCharArray();for (int i =0; i <c.length; i++) {char temp = c[i]; c[i] ='*';String changedStr =String.valueOf(c);if (seen.contains(changedStr)) {returntrue; }seen.add(changedStr); c[i] = temp; } }returnfalse; }}/*1.BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string.2.O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").*/
Follow up: Could you solve this problem in O(n * m) where n is the length of dict and m is the length of each string.