AlgoInsight

DSA problem

Words Within Two Edits of Dictionary

MediumTriesPattern: Triestop600AmazonGoogleMicrosoftAppleAdobe

You are given two string arrays queries and dictionary. All words in each array consist of the same length n. Return a list of all words from queries that can be transformed into some word from dictionary by changing at most two characters in total. A "change" replaces a single character at one position with any other character; positions can be changed independently as long as the total number of differing positions is at most two.

Since every query and every dictionary word has the same length n, "edits" here means Hamming distance, not full Levenshtein distance — we count differing positions, not insertions or deletions. That simplification is key because it means we never have to align strings, only compare them character by character.

A brute-force approach compares every query against every dictionary word, costing O(|queries| * |dictionary| * n). With each array containing up to 100 entries and n up to 100, that is feasible but wasteful: dictionary words sharing prefixes are compared from scratch every time.

A trie collapses the shared work. Insert every dictionary word into a 26-child trie. For each query, run a DFS through the trie that tracks the current depth (position in the query) and the running mismatch count. At each level, descend into the child equal to the query's current character (no extra mismatch) and into every other non-null child (one extra mismatch), as long as the total mismatch count stays <= 2. When the DFS reaches the bottom of any path with mismatch <= 2, the query qualifies. The pruning keeps this efficient: branches with mismatch > 2 are pruned immediately, so the average work per query is far less than the brute-force bound.

Examples

Example 1
Input: queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"]
Output: ["word","note","wood"]
Explanation: "word" differs from "wood" by 1 character (d vs d). "note" differs from "joke" by 2 (n,t vs j,k) — actually n,t vs j,k → 2 edits. "wood" is in the dictionary exactly (0 edits). "ants" needs 3+ edits to reach any dictionary word.
Example 2
Input: queries = ["yes"], dictionary = ["not"]
Output: []
Explanation: Converting "yes" to "not" requires changing all three characters, which exceeds the limit of 2 edits.
Example 3
Input: queries = ["abc","xyz"], dictionary = ["abd","xya"]
Output: ["abc","xyz"]
Explanation: abc → abd is 1 edit; xyz → xya is 1 edit. Both qualify.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

triearraystringdepth-first-search

Browse all DSA problems