VISUALGO//PROBLEMS
determine if two strings are close · hash map / setmedium
word1
a
b
c
word2
b
c
a
freq1
·
freq2
·
result
·
ELEMENTS
word1
word2
Python
def closeStrings(word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
freq1 = {}
for ch in word1:
freq1[ch] = freq1.get(ch, 0) + 1
freq2 = {}
for ch in word2:
freq2[ch] = freq2.get(ch, 0) + 1
# Same character set
if set(freq1.keys()) != set(freq2.keys()):
return False
# Same sorted frequency list
return sorted(freq1.values()) == sorted(freq2.values())