#2452

Words Within Two Edits of Dictionary

Medium
ArrayStringTrieHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k * 26^2)
Space
O(1)
O(n)
💡

Intuition

Time O(n * k * 26^2)Space O(n)

Instead of comparing each query with every dictionary word, we can use a set to efficiently check for potential matches by generating all possible words that are two edits away from each query.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a set to store all words in the dictionary for O(1) lookups.
  2. 2Step 2: For each word in queries, generate all possible words with 0, 1, or 2 edits.
  3. 3Step 3: Check if any of the generated words exist in the dictionary set.
  4. 4Step 4: If a match is found, add the query word to the results list.
  5. 5Step 5: Return the results list.
solution.py20 lines
1def generate_words(word):
2    alphabet = 'abcdefghijklmnopqrstuvwxyz'
3    words = set()
4    for i in range(len(word)):
5        for c in alphabet:
6            if c != word[i]:
7                words.add(word[:i] + c + word[i+1:])
8                for c2 in alphabet:
9                    if c2 != word[i] and c2 != c:
10                        words.add(word[:i] + c2 + word[i+1:])
11    return words
12
13def two_edit_words(queries, dictionary):
14    dict_set = set(dictionary)
15    result = []
16    for query in queries:
17        possible_words = generate_words(query)
18        if any(word in dict_set for word in possible_words):
19            result.append(query)
20    return result

Complexity note: This complexity arises from generating potential words for each query with two edits, where k is the length of the words (constant). The space complexity is O(n) due to the dictionary set.

  • 1Understanding character differences is key to solving this problem.
  • 2Using a set for quick lookups can significantly improve efficiency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.