Words Within Two Edits of Dictionary - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"]
Output: ["word","note","wood"]
💡 Note: "word" → "wood" (1 edit: r→o), "note" → "joke" (1 edit: n→j), "wood" → "wood" (0 edits), "ants" needs 3 edits minimum
Example 2 — Two Edits Required
$ Input: queries = ["yes"], dictionary = ["not"]
Output: []
💡 Note: "yes" → "not" requires 3 edits (y→n, e→o, s→t), which exceeds the maximum of 2
Example 3 — Multiple Matches
$ Input: queries = ["leet","code"], dictionary = ["lead","cool"]
Output: ["leet","code"]
💡 Note: "leet" → "lead" (2 edits: e→a, t→d), "code" → "cool" (2 edits: d→l, e→l)

Constraints

  • 1 ≤ queries.length, dictionary.length ≤ 100
  • 1 ≤ queries[i].length, dictionary[i].length ≤ 100
  • queries[i] and dictionary[i] consist of only lowercase English letters
  • All queries[i] and dictionary[i] have the same length

Visualization

Tap to expand
Words Within Two Edits: Find Close MatchesQuerieswordnoteantsDictionarywoodjokemoatResultwordnoteCompare≤ 2 editsword → wood: 1 edit ✓note → joke: 1 edit ✓ants → moat: 3 edits ✗Check each query against all dictionary words, count character differences
Understanding the Visualization
1
Input
Queries: ["word","note","ants"] and Dictionary: ["wood","joke","moat"]
2
Process
Compare each query with all dictionary words, counting character differences
3
Output
Return queries that match within 2 edits: ["word","note"]
Key Takeaway
🎯 Key Insight: Only count character differences - if more than 2, the word cannot match within the limit
Asked in
Google 25 Facebook 18
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen