Intuition

  • This is a trick question. The trick is as long as you have:
    • The same amount of characters
    • The same characters
    • The count amount of each respective character is the same as the count amount for the count amount in the other string, irrespective of what that string is.
  • Then you return True, and otherwise False.
  • In practice, this can be achieved with a Counter.

Complexity

Runtime

Space

Code

More Efficient One Liner

class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values())
  • This gives you the count of a count:
word1="abc"
word2="bca"
Stdout
Counter({1: 3})
Counter({1: 3})

One Liner

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

With Variables

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

Cards

START Basic Front: Determine If Two Strings Are Close Back: Make certain the count of the counts of each character are the same.

END


References