KatInterview

Nearest Word Lookup Using Minimum Edit Operations

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingedit-distancedynamic-programmingstrings

Last updated

Compute Levenshtein distance with dynamic programming and pick, for each query, the closest dictionary word with a stable first-index tie-break.

Nearest Word Lookup

You are given a dictionary of words, words, and a list of search terms, terms. For every search term, determine which dictionary word is the most similar to it, where similarity is measured by edit distance.

Edit distance

The edit distance between two strings is the smallest number of single-character operations needed to turn one string into the other. The allowed operations are:

  • insert one character at any position,
  • delete one character,
  • replace one character with a different character.

Each operation costs 1.

Task

For each term in terms, in order, find the word in words whose edit distance to that term is the smallest, and add that word to the output list.

Tie-break rule: if several words share the smallest distance, choose the one with the lowest index in words (the one that appears first). If the same word occurs more than once, this simply means the first occurrence is used; the returned string is the same either way.

Return a list with one chosen word per search term, in the same order as terms.

Details

  • A word or a term may be an empty string. The distance between an empty string and another string equals the length of the other string.
  • The distance between two identical strings is 0.

Constraints

  • 1 <= len(words) <= 500
  • 1 <= len(terms) <= 100
  • Each string has length between 0 and 100 inclusive.
  • All strings contain only lowercase English letters.

Examples

Example 1

Input: find_nearest_words(['apple', 'apply', 'apricot'], ['aple'])

Output: ['apple']

Example 2

Input: find_nearest_words(['cat', 'bat', 'rat'], ['hat'])

Output: ['cat']

Hints

Hint 1

Define dp[i][j] as the edit distance between the first i characters of one string and the first j characters of the other; the base cases are dp[i][0] = i and dp[0][j] = j.

Hint 2

Each cell is the minimum of three options: delete (dp[i-1][j] + 1), insert (dp[i][j-1] + 1), or match/replace (dp[i-1][j-1] plus 0 if the characters are equal, else 1). Only the previous row is needed, so two rows suffice.

Hint 3

When scanning the words for one term, update the best answer only when a distance is strictly smaller than the best so far. This automatically keeps the earliest word on ties.