Nearest Word Lookup Using Minimum Edit Operations
Dynamic ProgrammingAuto-graded · 22 test casesLast 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) <= 5001 <= len(terms) <= 100- Each string has length between
0and100inclusive. - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem splits into two parts: computing the edit distance between two strings, and selecting the best word for each term.
Edit distance (dynamic programming). Let dp[i][j] be the edit distance between the first i characters of string a and the first j characters of string b.
- Base cases:
dp[i][0] = i(delete allicharacters) anddp[0][j] = j(insert alljcharacters). - Transition:
dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + (a[i-1] != b[j-1])). These are deletion, insertion, and match/replace respectively.
Row i depends only on row i-1, so two rolling rows are enough. Putting the shorter string on the column axis reduces memory to O(min(|a|, |b|)); this is safe because edit distance is symmetric (insertion and deletion are inverse operations with equal cost).
Selection. For each term, scan the words in order, starting with the first as the current best. Replace the best only when a distance is strictly smaller. Because the scan goes in index order and ties never replace the best, the earliest word achieving the minimum is kept.
Why it is correct
The last operation in an optimal transformation of a[:i] into b[:j] is a deletion of a[i-1], an insertion of b[j-1], or an alignment of the two last characters (free if equal, cost 1 otherwise). Each case reduces to a smaller subproblem, and taking the minimum over all three covers every optimal solution. The strict < comparison guarantees the lowest-index word wins ties.
Complexity
Let W be the number of words, T the number of terms, and L the maximum string length.
- Time: O(T · W · L²), about 5·10^8 elementary steps in the worst case by the loose bound, with each pair costing O(|term| · |word|).
- Space: O(L) for the rolling rows, plus O(T) for the output.
Reference solution
from typing import List
def find_nearest_words(words: List[str], terms: List[str]) -> List[str]:
def distance(a, b):
if len(a) < len(b):
a, b = b, a
previous = list(range(len(b) + 1))
for i, char_a in enumerate(a, 1):
current = [i]
for j, char_b in enumerate(b, 1):
current.append(min(
previous[j] + 1,
current[j - 1] + 1,
previous[j - 1] + (char_a != char_b),
))
previous = current
return previous[-1]
result = []
for term in terms:
best_word = words[0]
best_distance = distance(best_word, term)
for word in words[1:]:
d = distance(word, term)
if d < best_distance:
best_word = word
best_distance = d
result.append(best_word)
return result