Practice › Strings
Close Strings
Medium · Strings · Asked at Amazon, Google, Microsoft
Two strings are close if you can turn one into the other using these operations any number of times:
- Swap any two characters (so the order does not matter).
- Pick two letters that both occur, and turn every
xintoyand everyyintoxat the same time.
Print YES if a and b are close, otherwise NO.
Input
Two lines: the strings a and b (lowercase letters).
Output
YES or NO.
Constraints
- 1 ≤ |a|, |b| ≤ 10^5
Operation 1 lets you rearrange freely; operation 2 lets you swap the counts of two letters that both appear. So they are close exactly when both use the same set of letters and the sorted lists of letter counts are equal.
Example 1
Input
abc bca
Output
YES
Example 2
Input
a aa
Output
NO
Example 3
Input
cabbba abbccc
Output
YES
Hints
- Swapping characters means only the counts of each letter matter.
- The second operation exchanges the counts of two letters that both appear — it cannot create a new letter.
- So compare the set of letters and the multiset of counts.
Approach
Count the letters of both strings. They are close iff (1) exactly the same letters appear in both (a letter with count 0 in one and > 0 in the other can never be fixed), and (2) after sorting, the two count arrays are equal (operation 2 can permute counts among present letters arbitrarily). Equal lengths follow automatically from (2).
Complexity: O(n + 26 log 26) time · O(26) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
vector<int> ca(26, 0), cb(26, 0);
for (char c : a) ca[c - 'a']++;
for (char c : b) cb[c - 'a']++;
for (int i = 0; i < 26; i++)
if ((ca[i] > 0) != (cb[i] > 0)) {
cout << "NO\n";
return 0;
}
sort(ca.begin(), ca.end());
sort(cb.begin(), cb.end());
cout << (ca == cb ? "YES" : "NO") << "\n";
return 0;
}Python solution
import sys
from collections import Counter
a, b = sys.stdin.read().split()[:2]
ca, cb = Counter(a), Counter(b)
ok = set(ca) == set(cb) and sorted(ca.values()) == sorted(cb.values())
print("YES" if ok else "NO")Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String a = br.readLine().trim(), b = br.readLine().trim();
int[] ca = new int[26], cb = new int[26];
for (char c : a.toCharArray()) ca[c - 'a']++;
for (char c : b.toCharArray()) cb[c - 'a']++;
for (int i = 0; i < 26; i++)
if ((ca[i] > 0) != (cb[i] > 0)) {
System.out.println("NO");
return;
}
Arrays.sort(ca);
Arrays.sort(cb);
System.out.println(Arrays.equals(ca, cb) ? "YES" : "NO");
}
}