Nearest String Match Under Edit Distance

Medium · Coding & Algorithms · Backend Engineer · Online Assessment

Problem Statement

Given a list of reference strings candidates and a list of search strings queries, select for every string in queries the entry in candidates that requires the fewest single-character edits to match it.

The Levenshtein edit distance between two strings a and b is the minimum number of elementary edits needed to convert a into b, where each edit is one of:

  • Insertion of a single character anywhere in the string,
  • Deletion of a single character from the string, or
  • Substitution of one character for another.

Whenever two or more strings in candidates tie for the smallest edit distance to a query, break the tie deterministically by choosing the candidate at the smallest index (earliest position) in candidates.

Implement:

def find_closest_candidates(candidates: List[str], queries: List[str]) -> List[str]:

Return a list of length len(queries) where item k is the winning candidate for queries[k].

Examples

Example 1

Input:
  candidates = ["stone", "storm", "store", "stony"]
  queries = ["storn", "stne"]
Output: ["storm", "stone"]
  • For "storn", the edit distances to ["stone", "storm", "store", "stony"] are [2, 1, 1, 2] (changing 'n' to 'm' gives "storm" in 1 edit, and changing 'n' to 'e' gives "store" in 1 edit). Because "storm" appears before "store" in candidates, "storm" is chosen.
  • For "stne", inserting 'o' produces "stone" in 1 edit (distances [1, 3, 2, 2]), so "stone" is chosen.

Example 2

Input:
  candidates = ["plank", "blank", "flank"]
  queries = ["clank"]
Output: ["plank"]

Every candidate is 1 character substitution away from "clank". Even though "blank" and "flank" are lexicographically smaller, "plank" appears first at index 0 and wins the tie-break.

Constraints

  • 1 <= len(candidates) <= 500
  • 1 <= len(queries) <= 100
  • 0 <= len(s) <= 100 for every string s in candidates and queries
  • Every string consists solely of lowercase English letters ('a'–'z')

Step-by-step walkthrough

  1. Understand the goal and the tie-break rule

    We are given candidates (1 to 500 lowercase strings) and queries (1 to 100 lowercase strings), each of length 0 to 100.

    For every string in queries, we must pick the string in candidates with the smallest Levenshtein edit distance — the minimum number of single-character insertions, deletions, and substitutions needed to turn the query into that candidate.

    If two or more candidates tie for the smallest distance, we must return the one that appears earliest in candidates. Our job cleanly splits into two pieces: 1. A helper edit_distance(s1, s2) that computes the exact edit distance between two strings. 2. A loop in find_closest_candidates that scans candidates for each query while preserving the earliest winner on ties.

  2. Why plain recursion explodes

    Suppose we compare the last characters of s1 and s2: - If either string is empty, the only option is to insert or delete every character of the other string, costing its length. - If the last characters match (s1[-1] == s2[-1]), we align them for 0 cost and solve the remaining prefixes s1[:-1] and s2[:-1]. - If they differ, we pay 1 edit and take the best of three choices: 1. Substitute s1[-1] with s2[-1] -> solve (s1[:-1], s2[:-1]), 2. Delete s1[-1] -> solve (s1[:-1], s2), 3. Insert s2[-1] at the end of s1 -> solve (s1, s2[:-1]).

    Writing this directly as an uncached recursive function branches three ways on every mismatch. Because different sequences of moves reach the exact same pair of prefix lengths over and over, plain recursion takes O(3^L) time — completely unusable for 100-character strings.

  3. Build a dynamic programming table over prefixes

    Notice that every recursive call only depends on two integers: how many characters of s1 remain (i) and how many characters of s2 remain (j). For lengths N and M, there are only (N + 1) * (M + 1) distinct (i, j) pairs!

    Let dp[i][j] be the minimum edit distance between s1[:i] (the first i characters of s1) and s2[:j] (the first j characters of s2): - Row 0 (i = 0): s1[:0] is "". Reaching s2[:j] requires j insertions, so dp[0][j] = j. - Column 0 (j = 0): s2[:0] is "". Reaching "" from s1[:i] requires i deletions, so dp[i][0] = i. - Every interior cell (i, j) looks at just three already-computed neighbors:

               j - 1                   j
           +-----------------------+-----------------------+
     i - 1 | dp[i-1][j-1]          | dp[i-1][j]            |
           |  \  +0 if chars match |  |  +1 (delete s1[i-1])|
           |   \ +1 (substitute)   |  v                    |
           +-----------------------+-----------------------+
       i   | dp[i][j-1]   +1  ---> | dp[i][j] = min(...)   |
           | (insert s2[j-1])      |                       |
           +-----------------------+-----------------------+
    

    When s1[i - 1] == s2[j - 1], dp[i - 1][j - 1] is never worse than dp[i - 1][j] + 1 or dp[i][j - 1] + 1 (adjacent DP cells differ by at most 1), so taking min of all three options works cleanly in both cases.

  4. Shrink memory to two rows

    Look again at the diagram above: to fill row i, we only ever read row i - 1 (prev_row) and the left neighbor curr_row[j - 1] inside row i. Older rows 0 .. i - 2 are never read again!

    Even better, because insertion and deletion both cost 1, Levenshtein distance is symmetric: edit_distance(s1, s2) == edit_distance(s2, s1). Swapping the strings when len(s2) > len(s1) ensures s2 is always the shorter string, so each row holds only min(len(s1), len(s2)) + 1 integers (O(min(N, M)) space).

    def edit_distance(s1: str, s2: str) -> int:
        """Compute the Levenshtein edit distance using two rolling DP rows."""
        # Unit-cost edit distance is symmetric (inserting into s1 equals deleting from s2),
        # so make s2 the shorter string to keep each DP row at min(len(s1), len(s2)) + 1 ints.
        if len(s2) > len(s1):
            s1, s2 = s2, s1
    
        # prev_row[j]: minimum edits between prefix s1[:i-1] and prefix s2[:j].
        # Base case for i = 0 (empty s1 prefix): transforming "" into s2[:j] takes j insertions.
        prev_row = list(range(len(s2) + 1))
    
        # Fill the DP table one row (one character of s1) at a time.
        for i in range(1, len(s1) + 1):
            # curr_row[0] = i because transforming s1[:i] into "" takes i deletions.
            curr_row = [i] + [0] * len(s2)
            for j in range(1, len(s2) + 1):
                if s1[i - 1] == s2[j - 1]:
                    match_or_sub_cost = prev_row[j - 1]
                else:
                    match_or_sub_cost = prev_row[j - 1] + 1
    
                delete_cost = prev_row[j] + 1
                insert_cost = curr_row[j - 1] + 1
                curr_row[j] = min(match_or_sub_cost, delete_cost, insert_cost)
    
            prev_row = curr_row
    
        return prev_row[len(s2)]
    
  5. Pick the closest candidate with deterministic tie-breaking

    Because the constraints guarantee len(candidates) >= 1, we can start each query with candidates[0] as our tentative champion (best_index = 0, best_distance = edit_distance(query, candidates[0])) and scan i from 1 upward.

    Pay close attention to the comparison if distance < best_distance:: - Using strict < means a later candidate with the same distance does not overwrite best_index, so the earliest tied candidate automatically wins. - Using <= by mistake would return the last tied candidate instead!

    def find_closest_candidates(candidates: List[str], queries: List[str]) -> List[str]:
        results: List[str] = []
    
        # Evaluate each query independently against every candidate in original list order.
        for query in queries:
            best_index = 0
            best_distance = edit_distance(query, candidates[0])
    
            for i in range(1, len(candidates)):
                distance = edit_distance(query, candidates[i])
                # Use strict '<' (not '<=') so ties keep the earliest candidate in `candidates`.
                if distance < best_distance:
                    best_distance = distance
                    best_index = i
    
            results.append(candidates[best_index])
    
        return results
    
  6. Trace Example 1 and Example 2

    In Example 1, candidates = ["stone", "storm", "store", "stony"] and queries = ["storn", "stne"]. Let's trace the DP rows when comparing "stne" (len 4, swapped into columns s2) against "stone" (len 5, rows s1):

              ""  s  t  n  e
        ""     0  1  2  3  4   <- initial prev_row
        s      1  0  1  2  3
        t      2  1  0  1  2
        o      3  2  1  1  2   <- deleting 'o' costs prev_row[2] + 1 = 0 + 1 = 1
        n      4  3  2  1  2
        e      5  4  3  2  1   <- final answer prev_row[4] = 1
    

    Checking both queries in order: - Query "storn": - i = 0 ("stone"): distance = 2 -> best_index = 0, best_distance = 2. - i = 1 ("storm"): distance = 1 (substitute 'n' -> 'm') -> 1 < 2 is True -> best_index = 1, best_distance = 1. - i = 2 ("store"): distance = 1 (substitute 'n' -> 'e') -> 1 < 1 is False ("storm" keeps the lead). - i = 3 ("stony"): distance = 2 -> 2 < 1 is False. - Query "stne": - i = 0 ("stone"): distance = 1 -> best_index = 0, best_distance = 1, and later distances 3, 2, 2 never beat 1.

    Result for Example 1: ["storm", "stone"].

    In Example 2, query = "clank" and candidates = ["plank", "blank", "flank"]: - i = 0 ("plank"): distance = 1 -> best_index = 0, best_distance = 1. - i = 1 ("blank"): distance = 1 -> 1 < 1 is False ("plank" stays). - i = 2 ("flank"): distance = 1 -> 1 < 1 is False ("plank" stays).

    Result for Example 2: ["plank"].

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def edit_distance(s1: str, s2: str) -> int:
        """Compute the Levenshtein edit distance using two rolling DP rows."""
        # Unit-cost edit distance is symmetric (inserting into s1 equals deleting from s2),
        # so make s2 the shorter string to keep each DP row at min(len(s1), len(s2)) + 1 ints.
        if len(s2) > len(s1):
            s1, s2 = s2, s1
    
        # prev_row[j]: minimum edits between prefix s1[:i-1] and prefix s2[:j].
        # Base case for i = 0 (empty s1 prefix): transforming "" into s2[:j] takes j insertions.
        prev_row = list(range(len(s2) + 1))
    
        # Fill the DP table one row (one character of s1) at a time.
        for i in range(1, len(s1) + 1):
            # curr_row[0] = i because transforming s1[:i] into "" takes i deletions.
            curr_row = [i] + [0] * len(s2)
            for j in range(1, len(s2) + 1):
                if s1[i - 1] == s2[j - 1]:
                    match_or_sub_cost = prev_row[j - 1]
                else:
                    match_or_sub_cost = prev_row[j - 1] + 1
    
                delete_cost = prev_row[j] + 1
                insert_cost = curr_row[j - 1] + 1
                curr_row[j] = min(match_or_sub_cost, delete_cost, insert_cost)
    
            prev_row = curr_row
    
        return prev_row[len(s2)]
    
    
    def find_closest_candidates(candidates: List[str], queries: List[str]) -> List[str]:
        results: List[str] = []
    
        # Evaluate each query independently against every candidate in original list order.
        for query in queries:
            best_index = 0
            best_distance = edit_distance(query, candidates[0])
    
            for i in range(1, len(candidates)):
                distance = edit_distance(query, candidates[i])
                # Use strict '<' (not '<=') so ties keep the earliest candidate in `candidates`.
                if distance < best_distance:
                    best_distance = distance
                    best_index = i
    
            results.append(candidates[best_index])
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of building a spell-checker for a search bar: when a shopper types "stne", you want to score every catalog word by the fewest single-letter fixes — inserting a missing letter, deleting an extra letter, or replacing one letter — needed to turn "stne" into that word, keeping the earliest catalog word whenever two words tie. Rather than guessing whole sequences of edits at once, we solve tiny prefix pairs ("" vs "", "s" vs "s", "st" vs "st", and so on) in a grid where each square reuses three neighboring squares directly above and to its left. This technique is dynamic programming (solving a problem by saving the answers to smaller overlapping subproblems in a table so each subproblem is computed only once), combined with a rolling array (keeping only the previous row and current row in memory because older rows are never read again).

Why do simpler approaches fail? Comparing characters index by index (query[k] != candidate[k]) breaks immediately when a single insertion shifts every remaining character out of place — "stne" vs "stone" would look like 2 mismatches plus a length penalty instead of 1 insertion. Conversely, exploring all possible insertions, deletions, and substitutions via plain recursion without a table re-solves identical prefix pairs exponentially many times (O(3^L) steps), hanging on strings well before length 100.

Let's walk through query = "ab" against candidates = ["xb", "yb", "abc"]. First, edit_distance("xb", "ab") fills rows of length min(2, 2) + 1 = 3:

          ""  a  b
    ""  [  0, 1, 2 ]   <- prev_row (0, 1, 2 insertions from "")
    x   [  1, 1, 2 ]   <- 'x'!='a' -> sub 0+1=1; 'x'!='b' -> min(sub 1+1, del 2+1, ins 1+1)=2
    b   [  2, 2, 1 ]   <- 'b'=='b' -> free match from prev_row[1]=1 -> distance = 1

Scan candidates for query "ab":
  i=0 "xb"  -> dist 1 -> best = (idx 0, dist 1)
  i=1 "yb"  -> dist 1 -> 1 < 1 is False (tie keeps earlier "xb")
  i=2 "abc" -> dist 1 -> 1 < 1 is False (tie still keeps "xb") -> returns "xb"

Complexity

Let Q be len(queries), C be len(candidates), and L be the maximum string length (L <= 100).

  • Time: O(Q * C * L^2). For each of the Q queries, we compare against all C candidates; each edit_distance call fills (|s1| + 1) * (|s2| + 1) cells with O(1) arithmetic per cell (3 additions and one min), bounded by O(L^2) work per pair.
  • Space: O(L) extra (plus O(Q) for the returned results list). Because we swap the two input strings so s2 is the shorter one and keep only prev_row and curr_row, edit_distance allocates just two lists of min(|query|, |candidate|) + 1 integers at any moment.

Edge cases

  • Empty query (""): Transforming "" into candidate requires len(candidate) insertions, so the earliest shortest candidate wins.
  • Empty candidate (""): Transforming query into "" costs len(query) deletions; "" wins whenever every non-empty candidate is at least len(query) edits away.
  • Multiple candidates tied for minimum distance: Strict < ensures candidates[0] beats candidates[1] on a tie regardless of alphabetical order (["zzz", "aaa"] on "bbb" returns "zzz").
  • Exact match (distance == 0): Distance 0 is the smallest possible non-negative distance, so the earliest exact match always wins even if near matches appear before it.
  • Repeated queries: Each query in queries produces its own entry in results at the matching index.

Common mistakes

  • Writing distance <= best_distance instead of distance < best_distance: Using <= overwrites the winner on ties and returns the last tied candidate ("flank" instead of "plank" in Example 2).
  • Charging 2 for substitution (delete + insert): Standard Levenshtein distance counts substitution as 1 operation ("kitten" to "sitting" is 3 edits, not 5).
  • Forgetting curr_row[0] = i on each new row: Leaving curr_row[0] as 0 makes deleting the prefix s1[:i] free and undercounts distances.
  • Updating a single row in place without saving the diagonal value: Overwriting row[j - 1] before reading the old prev_row[j - 1] corrupts the substitution transition; using two lists (prev_row and curr_row) prevents this cleanly.
  • Swapping s1 and s2 when insertion and deletion costs differ: Swapping is valid only when cost_insert == cost_delete.

Alternative approaches

  • Branch-and-bound early exit (cap = best_distance): Two properties let us skip wasted DP work without changing worst-case complexity: first, abs(len(s1) - len(s2)) is always a lower bound on edit distance because each edit changes length by at most 1; second, every edit path from (0, 0) to (|s1|, |s2|) must pass through every row i with non-negative step costs, so min(curr_row) never exceeds the final distance. Whenever abs(len(query) - len(candidate)) >= best_distance or min(curr_row) >= best_distance, that candidate cannot strictly beat best_distance and can be abandoned immediately.
  • Full (len(s1) + 1) x (len(s2) + 1) 2D table: Uses O(L^2) space for the same O(L^2) time; prefer it when a follow-up asks you to backtrack and print the exact sequence of edit operations.

Follow-up questions

  • How would you speed up lookups if the candidate dictionary grew to one million words? Scanning a million candidates with full DP per query is too slow, so we prune candidates and share prefix work. First, deduplicate identical candidates (keeping each string's earliest index) and group them by length so we visit length buckets in increasing order of abs(len(c) - len(q)), stopping once that length gap exceeds best_distance (at equality, only candidates with index < best_index need checking). Second, insert all candidates into a trie (a prefix tree where strings sharing a common prefix share the same path from the root) and compute one DP row per trie node during a depth-first search, pruning any subtree whose min(curr_row) >= best_distance, or index candidates in a BK-tree (a tree for metric spaces that groups words by edit distance to a pivot word) and use the triangle inequality (dist(q, c) >= |dist(q, pivot) - dist(pivot, c)|) to skip entire subtrees outside [d - best_distance, d + best_distance].
  • What drives the asymptotic runtime of your algorithm, and why do string lengths enter quadratically? Each DP state represents an alignment point (i, j) between prefix query[:i] (0 <= i <= |query|) and prefix candidate[:j] (0 <= j <= |candidate|). Because any prefix of query could align with any prefix of candidate before we inspect their characters, there are (|query| + 1) * (|candidate| + 1) cells to fill at O(1) work per cell, summing to O(Q * C * L^2) across Q queries and C candidates. You can beat O(L^2) per pair when you have a small distance cap k by using banded dynamic programming (computing only cells within diagonal band |i - j| <= k, since moving outside that band already requires more than k insertions or deletions), which drops per-pair work to O(k * L).
  • How would you adapt the dynamic programming recurrence and space optimization if insertions cost more than substitutions or deletions? Replace the unit + 1 increments with operation-specific weights for transforming s1 (the query, if edits are measured from query to candidate) into s2: base cases become prev_row[j] = j * cost_ins and curr_row[0] = i * cost_del, and transitions become match_or_sub_cost = prev_row[j - 1] + (0 if s1[i - 1] == s2[j - 1] else cost_sub), delete_cost = prev_row[j] + cost_del, and insert_cost = curr_row[j - 1] + cost_ins. Crucially, weighted edit distance is no longer symmetric once cost_ins != cost_del (inserting into s1 corresponds to deleting from s2), so you must not blindly swap s1 and s2 for space optimization unless you also swap cost_ins and cost_del at the same time.

Follow-up questions

Similar questions

More Target interview questions

All 2 Target questions →