277. Strings That Have Two Letters Swapped
Asked in
Strings That Have Two Letters Swapped
You are given a string name and a list of strings nameList. Return every string from nameList that can be made equal to name by swapping exactly two characters in that string.

Matching Rules

  • A candidate string must have the same length as name.
  • Exactly two positions in the candidate string must differ from name.
  • Swapping the characters at those two positions must make the candidate equal to name.
  • A candidate that is already equal to name is not a match because no two different characters need to be swapped.
  • Character comparisons are case-sensitive.
  • Return matching strings in the same order in which they appear in nameList.
  • If the same matching string appears multiple times, include every occurrence.

Method

Find Names With Two Letters Swapped

List<String> findNamesWithTwoLettersSwapped(String name, List<String> nameList)
  • name is the target string.
  • nameList contains the candidate strings.
  • Return all candidates that satisfy the matching rules.

Constraints

  • 1 ≤ name.length() ≤ 100,000
  • 1 ≤ nameList.size() ≤ 100,000
  • 1 ≤ nameList.get(i).length() ≤ 100,000
  • The total number of characters across all strings in nameList does not exceed 1,000,000.
  • name and every string in nameList contain English letters.

Examples

Example 1

findNamesWithTwoLettersSwapped(name = "market", nameList = List.of("makret", "market", "masket", "markte", "planet"))
Output: ["makret", "markte"]
In "makret", swapping 'k' and 'r' produces "market". In "markte", swapping the final two characters also produces "market".

Example 2

findNamesWithTwoLettersSwapped(name = "stone", nameList = List.of("stnoe", "sotne", "tones", "stone", "stnoe"))
Output: ["stnoe", "sotne", "stnoe"]
The matching strings differ from "stone" at exactly two positions, and swapping those characters produces the target. The duplicate occurrence is preserved.

Example 3

findNamesWithTwoLettersSwapped(name = "code", nameList = List.of("cope", "codes", "CODE", "deco"))
Output: []
None of the candidates can be transformed into "code" using exactly one swap of two characters.


Please use Laptop/Desktop or any other large screen to add/edit code.