Skip to content

1657. Determine if Two Strings Are Close 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
 public:
  bool closeStrings(string word1, string word2) {
    if (word1.length() != word2.length())
      return false;

    unordered_map<char, int> count1;
    unordered_map<char, int> count2;
    string s1;           // unique chars in word1
    string s2;           // unique chars in word2
    vector<int> freqs1;  // freqs of unique chars in word1
    vector<int> freqs2;  // freqs of unique chars in word2

    for (const char c : word1)
      ++count1[c];

    for (const char c : word2)
      ++count2[c];

    for (const auto& [c, freq] : count1) {
      s1 += c;
      freqs1.push_back(freq);
    }

    for (const auto& [c, freq] : count2) {
      s2 += c;
      freqs2.push_back(freq);
    }

    sort(begin(s1), end(s1));
    sort(begin(s2), end(s2));

    if (s1 != s2)
      return false;

    sort(begin(freqs1), end(freqs1));
    sort(begin(freqs2), end(freqs2));

    return freqs1 == freqs2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public boolean closeStrings(String word1, String word2) {
    if (word1.length() != word2.length())
      return false;

    Map<Character, Integer> count1 = new HashMap<>();
    Map<Character, Integer> count2 = new HashMap<>();

    for (final char c : word1.toCharArray())
      count1.put(c, count1.getOrDefault(c, 0) + 1);

    for (final char c : word2.toCharArray())
      count2.put(c, count2.getOrDefault(c, 0) + 1);

    if (!count1.keySet().equals(count2.keySet()))
      return false;

    List<Integer> freqs1 = new ArrayList<>(count1.values());
    List<Integer> freqs2 = new ArrayList<>(count2.values());

    Collections.sort(freqs1);
    Collections.sort(freqs2);

    return freqs1.equals(freqs2);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def closeStrings(self, word1: str, word2: str) -> bool:
    if len(word1) != len(word2):
      return False

    count1 = Counter(word1)
    count2 = Counter(word2)

    if count1.keys() != count2.keys():
      return False

    return sorted(count1.values()) == sorted(count2.values())