LeetCode 1790: Check if One String Swap Can Make Strings Equal

Problem Description

Explanation:

To solve this problem, we can follow these steps:

  1. Check if the two strings are already equal. If they are, return true.
  2. Iterate through both strings simultaneously and keep track of the characters that differ at the same index.
  3. If there are more than two differing characters or the differing characters are not the same when swapped, return false.
  4. If there are exactly two differing characters and they can be swapped to make the strings equal, return true.

Time Complexity:
The time complexity of this approach is O(n), where n is the length of the input strings.

Space Complexity:
The space complexity of this approach is O(1) as we are not using any extra space.

Solutions:

Solutions

class Solution {
    public boolean areAlmostEqual(String s1, String s2) {
        if (s1.equals(s2)) {
            return true;
        }

        int n = s1.length();
        int diffCount = 0;
        int[] diffIndexes = new int[2];

        for (int i = 0; i < n; i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                diffIndexes[diffCount] = i;
                diffCount++;
                if (diffCount > 2) {
                    return false;
                }
            }
        }

        return (diffCount == 2 && s1.charAt(diffIndexes[0]) == s2.charAt(diffIndexes[1]) &&
                s1.charAt(diffIndexes[1]) == s2.charAt(diffIndexes[0]));
    }
}

Loading editor...