FastPrepNearest Vocabulary Word

Nearest Vocabulary Word

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a vocabulary array vocabulary and an input string word, return word when it appears in the vocabulary. Otherwise, return the vocabulary entry with the smallest Levenshtein edit distance from word.

One edit inserts, deletes, or replaces one character. Matching is case-sensitive. If several entries have the same minimum distance, return the lexicographically smallest one. Return the empty string when the vocabulary is empty.

Function

nearestVocabularyWord(vocabulary: String[], word: String) → String

Examples

Example 1

vocabulary = ["cat","bat","rat"]word = "hat"return = "bat"

All three vocabulary words are one replacement away; bat is lexicographically smallest.

Example 2

vocabulary = ["dog","cat"]word = "dog"return = "dog"

The input already belongs to the vocabulary, so it is returned unchanged.

Constraints

  • 0 <= vocabulary.length <= 1000
  • 0 <= vocabulary[i].length, word.length <= 100
  • All strings contain only lowercase English letters.

More Microsoft problems

See Microsoft hiring insights
public String nearestVocabularyWord(String[] vocabulary, String word) {
  // Write your code here.
}
vocabulary["cat","bat","rat"]
word"hat"
expected"bat"
Checking account…