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 of Dictionary INPUT queries[] "word" "note" "ants" "wood" dictionary[] "wood" "joke" "moat" Example: "word" vs "wood" w o r d w o o d 2 differences = OK (max 2 edits) Same positions match ALGORITHM STEPS 1 Store Dictionary Keep all dict words for lookup 2 For Each Query Compare with every dict word 3 Count Differences Check char by char mismatch 4 Check if diff <= 2 Add to result if valid match Comparison Results: Query Best Match Diff word wood 2 OK note moat 2 OK ants -- 3+ NO wood wood 0 OK FINAL RESULT Words matching dictionary (within 2 edits) "word" "note" "wood" Output Array: ["word","note","wood"] 3 words matched out of 4 "ants" has no match within 2 edits Key Insight: For each query word, compare character-by-character with every dictionary word. Count mismatches at each position. If total mismatches <= 2 for ANY dictionary word, the query is valid. Early termination when differences exceed 2 optimizes performance. Time: O(Q * D * L) where Q=queries, D=dictionary, L=word length. TutorialsPoint - Words Within Two Edits of Dictionary | Hash Set for Dictionary Lookup
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