Intuition
All words have the same length, and a single edit changes one position. So an edit distance of at most 2 is the same as a Hamming distance of at most 2. For each query, scan the dictionary and check.
Explanation
Approach
- For each query word
q:- For each dictionary word
d:- Count mismatching positions; stop early if the count exceeds
2. - If the final count is
≤ 2, acceptqand move on.
- Count mismatching positions; stop early if the count exceeds
- For each dictionary word
Complexity
- Time:
O(q · d · n)whereq,dare the array sizes andnis the word length. With all bounded by 100, this is fine (≈10⁶ ops). - Space:
O(q)— output list.
Implementation
import java.util.*;
class Solution {
public List<String> twoEditWords(String[] queries, String[] dictionary) {
List<String> result = new ArrayList<>();
for (String q : queries) {
for (String d : dictionary) {
int mismatches = 0;
for (int i = 0; i < q.length(); i++) {
if (q.charAt(i) != d.charAt(i)) mismatches++;
if (mismatches > 2) break;
}
if (mismatches <= 2) {
result.add(q);
break;
}
}
}
return result;
}
}