Skip to content

1790. Check if One String Swap Can Make Strings Equal 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  // Similar to 859. Buddy Strings
  bool areAlmostEqual(string s1, string s2) {
    vector<int> diffIndices;
    for (int i = 0; i < s1.length(); ++i)
      if (s1[i] != s2[i])
        diffIndices.push_back(i);
    return diffIndices.empty() || (diffIndices.size() == 2 &&
                                   s1[diffIndices[0]] == s2[diffIndices[1]] &&
                                   s1[diffIndices[1]] == s2[diffIndices[0]]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public boolean areAlmostEqual(String s1, String s2) {
    List<Integer> diffIndices = new ArrayList<>();

    for (int i = 0; i < s1.length(); ++i)
      if (s1.charAt(i) != s2.charAt(i))
        diffIndices.add(i);

    return diffIndices.isEmpty() ||
        (diffIndices.size() == 2 &&
         s1.charAt(diffIndices.get(0)) == s2.charAt(diffIndices.get(1)) &&
         s1.charAt(diffIndices.get(1)) == s2.charAt(diffIndices.get(0)));
  }
}
1
2
3
4
5
6
7
8
class Solution:
  # Similar to 859. Buddy Strings
  def areAlmostEqual(self, s1: str, s2: str) -> bool:
    diffIndices = [i for i, (a, b) in enumerate(zip(s1, s2))
                   if a != b]
    return not diffIndices or (len(diffIndices) == 2 and
                               s1[diffIndices[0]] == s2[diffIndices[1]] and
                               s1[diffIndices[1]] == s2[diffIndices[0]])