#966
Vowel Spellchecker
MediumArrayHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a hash map for quick lookups and processes the queries in a single pass. By storing the original words in a map with their lowercase versions, we can efficiently check for matches and vowel replacements.
⚙️
Algorithm
3 steps- 1Step 1: Create a set from the wordlist for exact matches.
- 2Step 2: Create a hash map that maps lowercase words to their original case-sensitive versions.
- 3Step 3: For each query, check for an exact match, then a case-insensitive match, and finally check for vowel replacements using a loop.
solution.py25 lines
1def spellchecker(wordlist, queries):
2 wordset = set(wordlist)
3 lower_wordlist = {word.lower(): word for word in wordlist}
4 vowels = 'aeiou'
5 results = []
6 for query in queries:
7 if query in wordset:
8 results.append(query)
9 elif query.lower() in lower_wordlist:
10 results.append(lower_wordlist[query.lower()])
11 else:
12 found = False
13 for i in range(len(query)):
14 if query[i] in vowels:
15 for vowel in vowels:
16 modified_query = query[:i] + vowel + query[i+1:]
17 if modified_query.lower() in lower_wordlist:
18 results.append(lower_wordlist[modified_query.lower()])
19 found = True
20 break
21 if found:
22 break
23 if not found:
24 results.append('')
25 return resultsℹ
Complexity note: The optimal solution runs in O(n) time because we process each query in a single pass and use hash maps for quick lookups, making it efficient for large inputs.
- 1Using hash maps allows for quick lookups, significantly improving efficiency.
- 2Understanding the precedence of matching rules is crucial for implementing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.