[
string
counter
]
Leetcode 1657. Determine if Two Strings Are Close
https://leetcode.com/problems/determine-if-two-strings-are-close
Let us look more carefully at this problem:
- Operation 1 allows us to swap any two symbols, so what matters in the end not order of them, but how many of each symbol we have. Imagine we have
(6, 3, 3, 5, 6, 6)
frequencies of symbols, than we need to have the same frequencies for the second string as well. So, we need to check if we have the same elements, but in different order (that is one is anagramm of another), how we can efficiently check it? We can sort both of them and compare, or we can use Counter again to check if these two lists have the same elements! Yes, we use here Counter of Counter and to be honest I see it first time, but it is not that diffucult. - Operation 2 allows us to rename our letters, but we need to use the same letters: it means, that set of letters in first and second strings should be the same.
Complexity: time complexity is O(n)
: we create counters, and then again create counters. Space complexity is O(m)
, where m
is size of alphabet to keep our counters.
class Solution:
def closeStrings(self, w1, w2):
return set(w1) == set(w2) and Counter(Counter(w1).values()) == Counter(Counter(w2).values())
If you like the solution, you can upvote it on leetcode discussion section: Problem 1657