Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 5, 2025 22:36
Show Gist options
  • Save Ifihan/9abce9ca2f99cda7276e390a5d5b3815 to your computer and use it in GitHub Desktop.
Save Ifihan/9abce9ca2f99cda7276e390a5d5b3815 to your computer and use it in GitHub Desktop.
Check if One String Swap Can Make Strings Equal

Question

Approach

I first check if the two strings are already equal. If they are, I return True immediately since no swaps are needed. Otherwise, I identify the positions where the characters in s1 and s2 differ. I do this by iterating through both strings and collecting the indices where their characters do not match.

If the number of differences is more than two, I return False. If there is exactly one difference, I also return False since swapping requires at least two differing positions. However, if there are exactly two mismatches, I check whether swapping the mismatched characters in one of the strings would make the strings equal. If so, I return True; otherwise, I return False.

Implementation

class Solution:
    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        diff_indices = []  

    for i in range(len(s1)): 
        if s1[i] != s2[i]:
            diff_indices.append(i)

    if not diff_indices:
        return True

    if len(diff_indices) == 2:
        i, j = diff_indices
        return s1[i] == s2[j] and s1[j] == s2[i]

    return False

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment