Post

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

You are given two strings `s1` and `s2` of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return `true` if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return `false`.

Description

You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

Example 1:

Input: s1 = "bank", s2 = "kanb"
Output: true
  • For example, swap the first character with the last character of s2 to make “bank”.

Example 2:

Input: s1 = "attack", s2 = "defend"
Output: false
  • It is impossible to make them equal with one string swap.

Example 3:

Input: s1 = "kelb", s2 = "kelb"
Output: true
  • The two strings are already equal, so no string swap operation is required.

Constraints:

  • 1 <= s1.length, s2.length <= 100
  • s1.length == s2.length
  • s1 and s2 consist of only lowercase English letters.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    # Iteration
    # Time Complexity: BigO(N)
    # Space Complexity: BigO(1)
    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        dif1 = []
        dif2 = []

        for i in range(0, len(s1)):
            if s1[i] != s2[i]:
                dif1.append(s1[i])
                dif2.append(s2[i])
                if len(dif1) > 2:
                    return False

        if len(dif1) == 0 and len(dif2) == 0:
            return True
        elif len(dif1) == 1 and len(dif2) == 1:
            return False
        return dif1[0] == dif2[1] and dif2[0] == dif1[1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Iteration
 * Time Complexity: BigO(N)
 * Space Complexity: BigO(1)
 */
function areAlmostEqual(s1: string, s2: string): boolean {
  let dif1 = [];
  let dif2 = [];

  for (let i = 0; i < s1.length; i++) {
    if (s1[i] != s2[i]) {
      dif1.push(s1[i]);
      dif2.push(s2[i]);
      if (dif1.length > 2) return false;
    }
  }

  if (dif1.length == 0 && dif2.length == 0) return true;
  else if (dif1.length == 1 && dif2.length == 1) return false;
  return dif1[0] == dif2[1] && dif1[1] == dif2[0];
}
This post is licensed under CC BY 4.0 by the author.