Weighted Edit Distance with Swaps for Search Query Correction
Last updated: November 29, 2026
Quick Overview
Implement a distance between a typed search query and a candidate correction that allows insertions, deletions, substitutions, and adjacent character swaps, each with its own cost. Use it to decide whether 'recpie' should be corrected to 'recipe'.
0
0
0 solved
Implement a distance between a typed search query and a candidate correction that allows insertions, deletions, substitutions, and adjacent character swaps, each with its own cost. Use it to decide whether 'recpie' should be corrected to 'recipe'.
Typos are common in Pinterest search, especially on mobile keyboards where swapped letters dominate. This onsite question tests 2D dynamic programming, the subtle restriction of the optimal string alignment variant, and how weights change the recurrence.
What the Interviewer Expects
- Writes correct base rows and columns scaled by insertion and deletion cost
- Adds the transposition case only when the two adjacent characters are crossed
- Takes the min of transposition and two substitutions when swap cost is high
- Explains the optimal string alignment restriction versus full Damerau-Levenshtein
- Reduces space to three rolling rows or explains how
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Why does 'ca' to 'abc' give 3 here but 2 under unrestricted Damerau-Levenshtein?
- How would you use keyboard adjacency to make substitution cost depend on the letters?
- How would you find the best correction among a million vocabulary terms quickly?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Inputs: query a, candidate b, costs for substitution, insertion or deletion, and adjacent swap.
- Output: minimum total cost.
- A swap turns 'xy' into 'yx' in one operation. This version (optimal st...
High-Level Design
dp[i][j] is the cost to turn the first i chars of a into the first j chars of b. Transitions: delete a[i-1], insert b[j-1], match or substitute, and if the last two characters are crossed (a[i-1] == b...