Skip to content

Instantly share code, notes, and snippets.

@evolvingsam
Last active February 5, 2025 19:50
Show Gist options
  • Select an option

  • Save evolvingsam/917bcf85ab713457e9750a2a133582f7 to your computer and use it in GitHub Desktop.

Select an option

Save evolvingsam/917bcf85ab713457e9750a2a133582f7 to your computer and use it in GitHub Desktop.

Question

Approach

My approach involves first checking if the two strings, s1 and s2, are equal. If they are, we immediately return true since no swap is needed.

Next, I create a list(array) called diff to store, in a tuple, the characters at a particular index if they are different. Since I can only make one swap, if the length of my diff list is greater than 2 mid way in the loop, then I return false.

  • At the end of the loop, If the length of diff is 2 and the first tuple is the reverse of the second tuple in my diff list, then I'll return True, otherwise, I'll return False.

Implementation

    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        if s1 == s2:
            return True  # Strings are already equal

        diff = []
        for i, (c1, c2) in enumerate(zip(s1, s2)):
            if c1 != c2:
                diff.append((c1, c2))
                if len(diff) > 2:
                    return False 
        
        return len(diff) == 2 and diff[0] == diff[1][::-1]

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