Problem solution · C++

Determine if Two Strings Are Close

Determine if Two Strings Are Close: a C++ solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sorting and greedy selection
Source
walkccc LeetCode Solutions
Length
41 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sorting and greedy selection

For Determine if Two Strings Are Close, the implementation first exposes a useful order, then scans that order while making locally justified choices.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. Scan in order, maintaining the invariant that makes each local choice safe.

Code notes

  • 41 lines of C++ from the credited upstream file 1657.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 4 loop blocks detected.

Complexity

Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeDetermine if Two Strings Are Close · C++C++
Use this to learn the idea, then write your own version.
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;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗