Spell Checker - Problem

Given a misspelled word and a dictionary of correct words, implement a spell checker that suggests the closest match using edit distance (Levenshtein distance).

The edit distance between two strings is the minimum number of single-character operations (insertions, deletions, or substitutions) required to change one string into another.

Return the word from the dictionary that has the minimum edit distance to the misspelled word. If there are multiple words with the same minimum distance, return the lexicographically smallest one.

Input & Output

Example 1 — Basic Case
$ Input: word = "teh", dictionary = ["cat", "dog", "the", "hat"]
Output: "the"
💡 Note: Edit distances: 'teh' to 'cat' = 3, to 'dog' = 3, to 'the' = 1 (swap e and h), to 'hat' = 2. Minimum is 1, so return 'the'.
Example 2 — Multiple Matches
$ Input: word = "abc", dictionary = ["ab", "ac", "bc"]
Output: "ab"
💡 Note: Edit distances: 'abc' to 'ab' = 1 (delete c), to 'ac' = 1 (delete b), to 'bc' = 1 (delete a). All have distance 1, return lexicographically smallest: 'ab'.
Example 3 — Exact Match
$ Input: word = "hello", dictionary = ["hello", "world"]
Output: "hello"
💡 Note: Perfect match exists with distance 0, so return 'hello'.

Constraints

  • 1 ≤ word.length ≤ 100
  • 1 ≤ dictionary.length ≤ 100
  • 1 ≤ dictionary[i].length ≤ 100
  • word and dictionary[i] consist of lowercase English letters only

Visualization

Tap to expand
INPUTtehMisspelled WordDictionary:catdogthehatALGORITHM1Compare with each word2Calculate edit distance (DP)3Track minimum distance4Return best matchDP Table Example:0121teh → the = 1RESULTtheBest Match FoundEdit Distance: 1(Swap e and h)Other distances:cat: 3, dog: 3, hat: 2Key Insight:Dynamic programming calculates edit distance efficiently by building solutionsfrom smaller subproblems, avoiding exponential recursive recalculations.TutorialsPoint - Spell Checker | Space-Optimized Dynamic Programming
Asked in
Google 32 Microsoft 28 Amazon 24 Apple 18
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen