Description
You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.
In one edit you can take a word from queries, and change any letter in it to any other letter. Find all words from queries that, after a maximum of two edits, equal some word from dictionary.
Return a list of all words from queries, that match with some word from dictionary after a maximum of two edits. Return the words in the same order they appear in queries.
Example 1:
Input: queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"] Output: ["word","note","wood"] Explanation: - Changing the 'r' in "word" to 'o' allows it to equal the dictionary word "wood". - Changing the 'n' to 'j' and the 't' to 'k' in "note" changes it to "joke". - It would take more than 2 edits for "ants" to equal a dictionary word. - "wood" can remain unchanged (0 edits) and match the corresponding dictionary word. Thus, we return ["word","note","wood"].
Example 2:
Input: queries = ["yes"], dictionary = ["not"] Output: [] Explanation: Applying any two edits to "yes" cannot make it equal to "not". Thus, we return an empty array.
Constraints:
1 <= queries.length, dictionary.length <= 100n == queries[i].length == dictionary[j].length1 <= n <= 100- All
queries[i]anddictionary[j]are composed of lowercase English letters.
Solutions
This function finds all queries that can be transformed into at least one dictionary word with at most 2 character edits. For each query, it compares it character-by-character against every dictionary word, counting the differences (diff). If it finds a dictionary word that differs by 2 or fewer characters, it immediately adds the query to the result array and moves to the next query (using break). The loop also optimizes by breaking early if differences exceed 2 before checking all characters. Finally, it returns an array of all queries that had a close match in the dictionary.
/**
* @param {string[]} queries
* @param {string[]} dictionary
* @return {string[]}
*/
var twoEditWords = function(queries, dictionary) {
const n = queries[0].length;
let res = [];
for (const query of queries) {
for (const dict of dictionary) {
let diff = 0;
for (let k = 0; k < n; k++) {
if (query[k] !== dict[k]) {
diff++;
if (diff > 2) {
break;
}
}
}
if (diff <= 2) {
res.push(query);
break;
}
}
}
return res;
};