Problem Statement
leetcode problem link
My Solution [Accepted]
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
counter1 = Counter(word1)
counter2 = Counter(word2)
s1 = counter1.keys()
s2 = counter2.keys()
return sorted(counter1.values()) == sorted(counter2.values()) and sorted(s1) == sorted(s2)
public class Solution {
public bool CloseStrings(string word1, string word2) {
if (word1.Length != word2.Length)
return false;
var dict1 = new Dictionary<char, int>();
var dict2 = new Dictionary<char, int>();
var hashSet1 = new HashSet<char>(word1);
var hashSet2 = new HashSet<char>(word2);
var sortedList1 = hashSet1.ToList();
var sortedList2 = hashSet2.ToList();
sortedList1.Sort();
sortedList2.Sort();
foreach(var ch in word1) {
if (dict1.ContainsKey(ch))
dict1[ch]++;
else
dict1[ch] = 1;
}
foreach(var ch in word2) {
if (dict2.ContainsKey(ch))
dict2[ch]++;
else
dict2[ch] = 1;
}
var values1 = dict1.Values.ToList();
values1.Sort();
var values2 = dict2.Values.ToList();
values2.Sort();
return sortedList1.SequenceEqual(sortedList2) && values1.SequenceEqual(values2);
}
}
Improve CSharp Solution
public class Solution
{
public bool CloseStrings(string word1, string word2)
{
if (word1.Length != word2.Length)
return false;
int[] freq1 = new int[26];
int[] freq2 = new int[26];
foreach (char c in word1)
freq1[c - 'a']++;
foreach (char c in word2)
freq2[c - 'a']++;
// Check if both words use the exact same characters
for (int i = 0; i < 26; i++)
{
if ((freq1[i] == 0) != (freq2[i] == 0))
return false;
}
// Compare sorted frequency distributions
Array.Sort(freq1);
Array.Sort(freq2);
return freq1.SequenceEqual(freq2);
}
}
Editorial
Approach 1: Using HashMap
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
word1_elem_freq = Counter(word1)
word2_elem_freq = Counter(word2)
return set(word1_elem_freq) == set(word2_elem_freq) and sorted(word1_elem_freq.values()) == sorted(word2_elem_freq.values())
Approach 2: Using Frequency Array Map
class Solution {
public:
bool closeStrings(string word1, string word2) {
if (word1.size() != word2.size()) return false;
vector<int> word1Map(26, 0);
vector<int> word2Map(26, 0);
for (auto c : word1) {
word1Map[c - 'a']++;
}
for (auto c : word2) {
word2Map[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
if ((word1Map[i] == 0 && word2Map[i] > 0) ||
(word2Map[i] == 0 && word1Map[i] > 0)) {
return false;
}
}
sort(word1Map.begin(), word1Map.end());
sort(word2Map.begin(), word2Map.end());
return (word1Map == word2Map);
}
};