leetcode

Vowel Spellchecker - Link

Question Description

Given a wordlist and a list of queries, return a list of words from wordlist for each query based on the following rules in order of priority:

  1. Exact match
  2. Case-insensitive match
  3. Vowel error match (replace vowels with any vowel)
  4. If no match found, return empty string

Constraints


Approach

Why this approach works:

Alternative approaches considered:


Dry Run

Example Input:

wordlist = ["KiTe","kite","hare","Hare"]
queries = ["kite","Kite","kiTe","Hare","KARE"]

Step-by-step execution:

Final Answer = ["kite","kite","kiTe","Hare","hare"]


Solution

import java.util.*;

public class Solution {
    public String[] spellchecker(String[] wordlist, String[] queries) {
        Set<String> exactWords = new HashSet<>(Arrays.asList(wordlist));
        Map<String, String> caseInsensitiveMap = new HashMap<>();
        Map<String, String> vowelErrorMap = new HashMap<>();

        for (String word : wordlist) {
            String wordLower = word.toLowerCase();
            caseInsensitiveMap.putIfAbsent(wordLower, word);

            String wordVowelMasked = maskVowels(wordLower);
            vowelErrorMap.putIfAbsent(wordVowelMasked, word);
        }

        String[] ans = new String[queries.length];
        for (int i = 0; i < queries.length; i++) {
            String query = queries[i];

            if (exactWords.contains(query)) {
                ans[i] = query;
                continue;
            }

            String queryLower = query.toLowerCase();
            if (caseInsensitiveMap.containsKey(queryLower)) {
                ans[i] = caseInsensitiveMap.get(queryLower);
                continue;
            }

            String queryVowelMasked = maskVowels(queryLower);
            if (vowelErrorMap.containsKey(queryVowelMasked)) {
                ans[i] = vowelErrorMap.get(queryVowelMasked);
            } else {
                ans[i] = "";
            }
        }

        return ans;
    }

    private String maskVowels(String str) {
        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            if ("aeiou".indexOf(c) != -1)
                sb.append('*');
            else
                sb.append(c);
        }
        return sb.toString();
    }
}

Time and Space Complexity