SDE & MLE Prep

1657. Determine if Two Strings Are Close

Problem

Two strings are "close" if one can become the other using two operations any number of times: swap any two characters, or pick two letters that both occur and swap every occurrence of one with the other. Decide whether word1 and word2 are close.

Example: "cabbba" and "abbccc" → true; "a" and "aa" → false

Operation 1 (swap) means order doesn't matter; operation 2 (swap two letters' roles) means the multiset of counts can be reassigned among letters already present. So: same set of letters and same sorted list of counts.

Complexity: O(n) (+ sorting 26 counts).

class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        c1, c2 = Counter(word1), Counter(word2)
        return c1.keys() == c2.keys() and sorted(c1.values()) == sorted(c2.values())