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"in1edit, and changing'n'to'e'gives"store"in1edit). Because"storm"appears before"store"incandidates,"storm"is chosen. - For
"stne", inserting'o'produces"stone"in1edit (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) <= 5001 <= len(queries) <= 1000 <= len(s) <= 100for every stringsincandidatesandqueries- Every string consists solely of lowercase English letters (
'a'–'z')
Step-by-step walkthrough
Understand the goal and the tie-break rule
We are given
candidates(1to500lowercase strings) andqueries(1to100lowercase strings), each of length0to100.For every string in
queries, we must pick the string incandidateswith 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 helperedit_distance(s1, s2)that computes the exact edit distance between two strings. 2. A loop infind_closest_candidatesthat scanscandidatesfor each query while preserving the earliest winner on ties.Why plain recursion explodes
Suppose we compare the last characters of
s1ands2: - 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 for0cost and solve the remaining prefixess1[:-1]ands2[:-1]. - If they differ, we pay1edit and take the best of three choices: 1. Substitutes1[-1]withs2[-1]-> solve(s1[:-1], s2[:-1]), 2. Deletes1[-1]-> solve(s1[:-1], s2), 3. Inserts2[-1]at the end ofs1-> 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 for100-character strings.Build a dynamic programming table over prefixes
Notice that every recursive call only depends on two integers: how many characters of
s1remain (i) and how many characters ofs2remain (j). For lengthsNandM, there are only(N + 1) * (M + 1)distinct(i, j)pairs!Let
dp[i][j]be the minimum edit distance betweens1[:i](the firsticharacters ofs1) ands2[:j](the firstjcharacters ofs2): - Row0(i = 0):s1[:0]is"". Reachings2[:j]requiresjinsertions, sodp[0][j] = j. - Column0(j = 0):s2[:0]is"". Reaching""froms1[:i]requiresideletions, sodp[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 thandp[i - 1][j] + 1ordp[i][j - 1] + 1(adjacent DP cells differ by at most1), so takingminof all three options works cleanly in both cases.Shrink memory to two rows
Look again at the diagram above: to fill row
i, we only ever read rowi - 1(prev_row) and the left neighborcurr_row[j - 1]inside rowi. Older rows0 .. i - 2are 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 whenlen(s2) > len(s1)ensuress2is always the shorter string, so each row holds onlymin(len(s1), len(s2)) + 1integers (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)]Pick the closest candidate with deterministic tie-breaking
Because the constraints guarantee
len(candidates) >= 1, we can start each query withcandidates[0]as our tentative champion (best_index = 0,best_distance = edit_distance(query, candidates[0])) and scanifrom1upward.Pay close attention to the comparison
if distance < best_distance:: - Using strict<means a later candidate with the same distance does not overwritebest_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 resultsTrace Example 1 and Example 2
In Example 1,
candidates = ["stone", "storm", "store", "stony"]andqueries = ["storn", "stne"]. Let's trace the DP rows when comparing"stne"(len 4, swapped into columnss2) against"stone"(len 5, rowss1):"" 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] = 1Checking 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 < 2isTrue->best_index = 1,best_distance = 1. -i = 2 ("store"):distance = 1(substitute'n' -> 'e') ->1 < 1isFalse("storm"keeps the lead). -i = 3 ("stony"):distance = 2->2 < 1isFalse. - Query"stne": -i = 0 ("stone"):distance = 1->best_index = 0,best_distance = 1, and later distances3, 2, 2never beat1.Result for Example 1:
["storm", "stone"].In Example 2,
query = "clank"andcandidates = ["plank", "blank", "flank"]: -i = 0 ("plank"):distance = 1->best_index = 0,best_distance = 1. -i = 1 ("blank"):distance = 1->1 < 1isFalse("plank"stays). -i = 2 ("flank"):distance = 1->1 < 1isFalse("plank"stays).Result for Example 2:
["plank"].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 theQqueries, we compare against allCcandidates; eachedit_distancecall fills(|s1| + 1) * (|s2| + 1)cells withO(1)arithmetic per cell (3additions and onemin), bounded byO(L^2)work per pair. - Space:
O(L)extra (plusO(Q)for the returnedresultslist). Because we swap the two input strings sos2is the shorter one and keep onlyprev_rowandcurr_row,edit_distanceallocates just two lists ofmin(|query|, |candidate|) + 1integers at any moment.
Edge cases
- Empty query (
""): Transforming""intocandidaterequireslen(candidate)insertions, so the earliest shortest candidate wins. - Empty candidate (
""): Transformingqueryinto""costslen(query)deletions;""wins whenever every non-empty candidate is at leastlen(query)edits away. - Multiple candidates tied for minimum distance: Strict
<ensurescandidates[0]beatscandidates[1]on a tie regardless of alphabetical order (["zzz", "aaa"]on"bbb"returns"zzz"). - Exact match (
distance == 0): Distance0is 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
queriesproduces its own entry inresultsat the matching index.
Common mistakes
- Writing
distance <= best_distanceinstead ofdistance < best_distance: Using<=overwrites the winner on ties and returns the last tied candidate ("flank"instead of"plank"in Example 2). - Charging
2for substitution (delete + insert): Standard Levenshtein distance counts substitution as1operation ("kitten"to"sitting"is3edits, not5). - Forgetting
curr_row[0] = ion each new row: Leavingcurr_row[0]as0makes deleting the prefixs1[:i]free and undercounts distances. - Updating a single row in place without saving the diagonal value: Overwriting
row[j - 1]before reading the oldprev_row[j - 1]corrupts the substitution transition; using two lists (prev_rowandcurr_row) prevents this cleanly. - Swapping
s1ands2when insertion and deletion costs differ: Swapping is valid only whencost_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 most1; second, every edit path from(0, 0)to(|s1|, |s2|)must pass through every rowiwith non-negative step costs, somin(curr_row)never exceeds the final distance. Wheneverabs(len(query) - len(candidate)) >= best_distanceormin(curr_row) >= best_distance, that candidate cannot strictly beatbest_distanceand can be abandoned immediately. - Full
(len(s1) + 1) x (len(s2) + 1)2D table: UsesO(L^2)space for the sameO(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 exceedsbest_distance(at equality, only candidates withindex < best_indexneed 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 whosemin(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 prefixquery[:i](0 <= i <= |query|) and prefixcandidate[:j](0 <= j <= |candidate|). Because any prefix ofquerycould align with any prefix ofcandidatebefore we inspect their characters, there are(|query| + 1) * (|candidate| + 1)cells to fill atO(1)work per cell, summing toO(Q * C * L^2)acrossQqueries andCcandidates. You can beatO(L^2)per pair when you have a small distance capkby using banded dynamic programming (computing only cells within diagonal band|i - j| <= k, since moving outside that band already requires more thankinsertions or deletions), which drops per-pair work toO(k * L). - How would you adapt the dynamic programming recurrence and space optimization if insertions cost more than substitutions or deletions? Replace the unit
+ 1increments with operation-specific weights for transformings1(the query, if edits are measured from query to candidate) intos2: base cases becomeprev_row[j] = j * cost_insandcurr_row[0] = i * cost_del, and transitions becomematch_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, andinsert_cost = curr_row[j - 1] + cost_ins. Crucially, weighted edit distance is no longer symmetric oncecost_ins != cost_del(inserting intos1corresponds to deleting froms2), so you must not blindly swaps1ands2for space optimization unless you also swapcost_insandcost_delat the same time.
Follow-up questions
- How would you speed up lookups if the candidate dictionary grew to one million words?
- What drives the asymptotic runtime of your algorithm, and why do string lengths enter quadratically?
- How would you adapt the dynamic programming recurrence and space optimization if insertions cost more than substitutions or deletions?
Similar questions
- Thread-Safe Lowest-Index Seat Allocator
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One