#1790

Check if One String Swap Can Make Strings Equal

Easy
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the observation that we only need to check the positions where the characters differ between the two strings. If there are exactly two such positions, we can check if swapping those characters makes the strings equal.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a list to store indices where s1 and s2 differ.
  2. 2Step 2: Iterate through both strings and record the indices of differing characters.
  3. 3Step 3: If the number of differing indices is 0, return true (strings are already equal).
  4. 4Step 4: If the number of differing indices is not 2, return false (cannot be made equal with one swap).
  5. 5Step 5: Check if swapping the characters at the differing indices makes the strings equal.
solution.py12 lines
1# Full working Python code
2
3def canSwap(s1, s2):
4    if s1 == s2:
5        return True
6    diff = []
7    for i in range(len(s1)):
8        if s1[i] != s2[i]:
9            diff.append(i)
10    if len(diff) != 2:
11        return False
12    return s1[diff[0]] == s2[diff[1]] and s1[diff[1]] == s2[diff[0]]

Complexity note: The time complexity is O(n) because we only need to make a single pass through the strings to find differing characters. The space complexity is O(n) due to storing the indices of differing characters in a list.

  • 1If the strings are already equal, no swap is needed.
  • 2Only two differing positions can be swapped to make the strings equal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.