Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
For a four-character string, the allowed distance-two swaps are only positions zero with two and positions one with three. These swaps affect disjoint pairs, so every reachable arrangement is obtained by doing neither, either one, or both.
Approach
Write the second string as a,b,c,d and construct its four possible arrangements: the original, the even-position swap, the odd-position swap, and both swaps. Return whether the first string equals any of them. Swaps are reversible, so checking reachability from the second string is equivalent to checking from the first. Duplicate letters may make some arrangements equal without changing the result.
class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
a, b, c, d = s2
return s1 in (s2, c+b+a+d, a+d+c+b, c+d+a+b)Complexity analysis
Because both strings have fixed length 4, time and auxiliary space are O(1).
