Filter Words Reachable From a Target by One Character Swap
StringsModel answerLast updated
Given a target string and a list of words, return every word that becomes the target after swapping at most one pair of characters in that word, keeping input order.
You are given a string target and a list of strings words. Write a function that returns every entry of words that can be turned into target by swapping at most one pair of characters inside that entry.
A swap exchanges the characters at two different index positions of the same word. Performing no swap is allowed.
Function contract
find_similar(target: str, words: list[str]) -> list[str]
Rules
- Return the matching words in their original order.
- If the input contains duplicates, each matching copy appears in the output.
- Comparison is case-sensitive.
- Words whose length differs from the target never match, because a swap does not change length.
- An empty word matches an empty target.
Example
target = "doordash"
words = ["doordahs", "doordash", "odordash", "doorhsad", "doordas", "doordasx"]
output = ["doordahs", "doordash", "odordash"]
What to cover in your answer
- Clarify the semantics of "at most one swap" versus "exactly one swap" and explain how they differ for identical strings.
- Describe your algorithm and justify why it is correct.
- Give time and space complexity in terms of
N(number of words) andL(target length). - Provide working code and discuss the edge cases you would test.
- Be ready to explain how the solution changes for the "exactly one swap" variant, and how you would speed things up if the same word list were queried against many targets.
Hints
Hint 1
Think about which positions a single swap can change. Compare a word with the target position by position and look at the set of indices where they differ. How large can that set be?
Hint 2
Only two situations are fixable: no differing positions, or exactly two differing positions i and j where word[i] equals target[j] and word[j] equals target[i]. Explain why exactly one differing position can never be repaired by a swap.
Hint 3
You can stop scanning a word as soon as you see a third mismatch, and reject immediately on a length difference. For the 'exactly one swap' variant, the zero-mismatch case needs a repeated character in the word so that you can swap two equal letters.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract first
The wording matters here:
- At most one swap (this problem): an identical word always matches, because zero swaps is allowed.
- Exactly one swap (the classic Buddy Strings formulation): an identical word matches only if it contains a repeated character, so that swapping two equal letters leaves it unchanged.
I would confirm this with the interviewer, then also confirm: output keeps input order, duplicates are kept, matching is case-sensitive, and different lengths never match.
Core idea
Compare word and target position by position and collect the indices where they differ. Call this set D. A swap touches only two positions, so the size of D decides the outcome.
| Size of D | Result |
|---|---|
| 0 | Match. No swap is needed. |
| 1 | No match. A swap changes two positions or none, so it cannot fix a single mismatch. |
| 2 (indices i, j) | Match only if the characters cross: word[i] == target[j] and word[j] == target[i]. |
| 3 or more | No match. One swap fixes at most two positions. |
Why this is correct
If swapping positions i and j turns word into target, every other position must already agree, so D is a subset of {i, j}.
- |D| = 1, say only
idiffers. Positionjalready matches, soword[j] == target[j]. After the swap, positioniholdsword[j], which equalstarget[j]. For it to equaltarget[i]we needtarget[j] == target[i]. Positionjthen holdsword[i], which must equaltarget[j], soword[i] == target[i]. That contradictsibeing a mismatch. - |D| = 2. The swap must use exactly those two positions, and it works exactly when the characters cross.
- |D| = 0. Already equal.
So the conditions are both necessary and sufficient.
Algorithm
For each word:
- If
len(word) != len(target), reject in O(1). - Scan both strings together, appending each differing index to a small list. If the list grows past 2, reject immediately.
- If the list is empty, accept.
- If the list has exactly one element, reject.
- If it has two elements
i, j, accept only when the characters cross.
Collect accepted words in order.
Complexity
- Time: O(N · L). Each word is scanned once at most, and the early exits make typical cases faster. You cannot beat this in the worst case, because every character of every candidate may need to be read.
- Space: O(1) extra per word (the mismatch list holds at most 3 indices), plus the output list.
Code
from typing import List
def find_similar(target: str, words: List[str]) -> List[str]:
def one_swap_away(word: str) -> bool:
if len(word) != len(target):
return False
diff = []
for i, (a, b) in enumerate(zip(word, target)):
if a != b:
diff.append(i)
if len(diff) > 2:
return False
if not diff:
return True # zero swaps needed
if len(diff) != 2:
return False # a single mismatch cannot be fixed
i, j = diff
return word[i] == target[j] and word[j] == target[i]
return [w for w in words if one_swap_away(w)]
Check on the example: doordahs differs at the last two positions and the letters cross, so it matches. doordash is identical and matches. odordash differs in the first two positions with crossing letters, so it matches. doorhsad has four mismatches, doordas has a different length, and doordasx has one mismatch, so all three are rejected.
Variant: exactly one swap
Only the zero-mismatch branch changes. An identical word matches only if some character appears at least twice:
if not diff:
return len(set(word)) < len(word)
Then "ab" vs "ab" fails, while "aa" vs "aa" passes.
Edge cases to test
- Different lengths (including an empty word against a non-empty target).
- Empty target with an empty word: match.
- Identical words, with and without repeated letters (relevant for the exactly-one variant).
- One mismatch, such as
abcvsabd: reject. - Two mismatches that do not cross, such as
abvscd: reject. - Two mismatches that do cross, such as
abvsba: accept. - Three or more mismatches: reject, and the scan stops early.
- Duplicate words in the list: each copy is returned.
- Case differences:
Dashdoes not matchdahsunless you agree to normalize case.
Follow-ups
- Many targets against a fixed word list. Any word one swap away from the target is an anagram of it. Bucket the words by length, or by sorted-character signature, so each query runs the O(L) check only on words in the target's bucket.
- Unicode and case. Decide whether to casefold, and normalize to NFC so equivalent accented forms compare equal. Be careful that swapping code points is not the same as swapping user-visible characters.
- Up to k swaps. Counting mismatches is no longer enough. The minimum swaps between two permutations equals the number of mismatched positions minus the number of cycles in the position mapping. With repeated characters, finding the true minimum becomes harder and is typically solved with a BFS or a greedy search with care.
Common mistakes
- Treating "at most one" and "exactly one" as the same and mishandling identical strings.
- Accepting a single mismatch because the two strings have the same character multiset.
- Checking only that the two mismatched characters are equal to each other rather than that they cross.
- Forgetting the length check, or scanning the whole string after a third mismatch.
- Returning a de-duplicated or reordered list when the contract says to preserve order and duplicates.