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.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- 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.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool closeStrings(string word1, string word2) {4 if (word1.length() != word2.length())5 return false;6 7 unordered_map<char, int> count1;8 unordered_map<char, int> count2;9 string s1; 10 string s2; 11 vector<int> freqs1; 12 vector<int> freqs2; 13 14 for (const char c : word1)15 ++count1[c];16 17 for (const char c : word2)18 ++count2[c];19 20 for (const auto& [c, freq] : count1) {21 s1 += c;22 freqs1.push_back(freq);23 }24 25 for (const auto& [c, freq] : count2) {26 s2 += c;27 freqs2.push_back(freq);28 }29 30 ranges::sort(s1);31 ranges::sort(s2);32 33 if (s1 != s2)34 return false;35 36 ranges::sort(freqs1);37 ranges::sort(freqs2);38 return freqs1 == freqs2;39 }40};41