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
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);
    }

    ranges::sort(s1);
    ranges::sort(s2);

    if (s1 != s2)
      return false;

    ranges::sort(freqs1);
    ranges::sort(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
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.merge(c, 1, Integer::sum);

    for (final char c : word2.toCharArray())
      count2.merge(c, 1, Integer::sum);

    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
class Solution:
  def closeStrings(self, word1: str, word2: str) -> bool:
    if len(word1) != len(word2):
      return False

    count1 = collections.Counter(word1)
    count2 = collections.Counter(word2)
    if count1.keys() != count2.keys():
      return False

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