KatInterview

Filter Words Reachable From a Target by One Character Swap

StringsModel answer
MediumModel answerStringsstringstwo-pointerscharacter-frequency

Last 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

  1. Clarify the semantics of "at most one swap" versus "exactly one swap" and explain how they differ for identical strings.
  2. Describe your algorithm and justify why it is correct.
  3. Give time and space complexity in terms of N (number of words) and L (target length).
  4. Provide working code and discuss the edge cases you would test.
  5. 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.