Similar Problems

Similar Problems not available

Vowel Spellchecker - Leetcode Solution

Companies:

LeetCode:  Vowel Spellchecker Leetcode Solution

Difficulty: Medium

Topics: string hash-table array  

Problem Statement:

Given a wordlist, a query word, and an integer k, return the k closest matches to the query word in the wordlist. If there is a tie, include all words with the same score and sort alphabetically.

The closest matches are defined as the words that differ from the query word by at most one vowel (in any position).

Example:

Input: wordlist = ["KiTe","kite","hare","Hare"], query = "kite", k = 2

Output: ["kite","KiTe"]

Explanation: "KiTe" is the only word in the wordlist with a difference of one vowel from the query word "kite". The other word "kite" is an exact match, so it is also included in the output.

Solution:

The given problem can be solved using the concept of hashing. We can create three different hash maps for the given word list, each storing a different representation of the words:

  • Exact match map: This map stores all the exact words from the word list. The key for this map is the word itself, and the value is the index of the word in the list.
  • Capitalization map: This map stores the lowercase version of all words from the word list. The key for this map is the lowercase word, and the value is the index of the word in the list. This map is used to find the words that differ only in capitalization.
  • Vowel map: This map stores a representation of all words from the word list where all vowels are replaced by a "*", and the key for this map is the vowel-replaced word. The value of the map is a list of indices of words that have the same vowel-replaced representation. This map is used to find the words that differ only in vowels.

Once we have created these maps, we can start processing the query. We first compare the query word with the exact match map. If it is an exact match, we return the query word. Otherwise, we look for the lowercase version of the query word in the capitalization map. If we find a match, we return the corresponding word from the word list. If we cannot find a match in the exact match map or the capitalization map, we create a vowel-replaced representation of the query word and look for it in the vowel map. We then collect all the indices of the words that have the same vowel-replaced representation. We then iterate through all these indices and calculate the Levenshtein distance between the query word and the corresponding word from the word list. We maintain a priority queue of the k closest matches, sorted by Levenshtein distance and then by alphabetical order in case of ties.

The time complexity of this solution is O(nL), where n is the length of the word list and L is the maximum length of a word. The space complexity of this solution is O(nL).

Vowel Spellchecker Solution Code

1