Leetcode #2452: Words Within Two Edits of Dictionary
In this guide, we solve Leetcode #2452 Words Within Two Edits of Dictionary in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Trie, Array, String
Intuition
Prefix queries are most efficient with a trie.
Each character transitions to the next node in the tree.
Approach
Insert words into the trie and traverse by characters for queries.
Track terminal markers to distinguish full words from prefixes.
Steps:
- Build the trie.
- Traverse for each query.
- Return matches or validations.
Example
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"].
Python Solution
class Solution:
def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:
ans = []
for s in queries:
for t in dictionary:
if sum(a != b for a, b in zip(s, t)) < 3:
ans.append(s)
break
return ans
Complexity
The time complexity is , where and are the lengths of the arrays and respectively, and is the length of the word. The space complexity is O(total characters).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.