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())
assert Solution().closeStrings("abc", "bca") is True
assert Solution().closeStrings("a", "aa") is False
assert Solution().closeStrings("cabbba", "abbccc") is True
assert Solution().closeStrings("uau", "ssx") is False
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) return false;
int[] a = new int[26], b = new int[26];
for (char c : word1.toCharArray()) a[c - 'a']++;
for (char c : word2.toCharArray()) b[c - 'a']++;
for (int i = 0; i < 26; i++) if ((a[i] == 0) != (b[i] == 0)) return false;
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a, b);
}
}
func closeStrings(word1 string, word2 string) bool {
var c1, c2 [26]int
for _, c := range word1 {
c1[c-'a']++
}
for _, c := range word2 {
c2[c-'a']++
}
for i := range c1 {
if (c1[i] == 0) != (c2[i] == 0) { // same set of letters
return false
}
}
a, b := c1[:], c2[:]
sort.Ints(a)
sort.Ints(b)
return c1 == c2 // same multiset of counts (arrays sorted in place)
}