- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 48 lines of C++ from the credited upstream file 3267.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 8 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 4 int countPairs(vector<int>& nums) {5 int ans = 0;6 unordered_map<int, int> count;7 const int maxLen = to_string(ranges::max(nums)).length();8 9 for (const int num : nums) {10 const string digits =11 string(maxLen - to_string(num).length(), '0') + to_string(num);12 for (const int swap : getSwaps(digits))13 ans += count[swap];14 ++count[num];15 }16 17 return ans;18 }19 20 private:21 22 unordered_set<int> getSwaps(const string& digits) {23 const int n = digits.length();24 unordered_set<int> swaps{{stoi(digits)}};25 26 27 for (int i = 0; i < n; ++i)28 for (int j = i + 1; j < n; ++j) {29 string newDigits = digits;30 swap(newDigits[i], newDigits[j]);31 swaps.insert(stoi(newDigits));32 }33 34 35 for (int i1 = 0; i1 < n; ++i1)36 for (int j1 = i1 + 1; j1 < n; ++j1)37 for (int i2 = 0; i2 < n; ++i2)38 for (int j2 = i2 + 1; j2 < n; ++j2) {39 string newDigits = digits;40 swap(newDigits[i1], newDigits[j1]);41 swap(newDigits[i2], newDigits[j2]);42 swaps.insert(stoi(newDigits));43 }44 45 return swaps;46 }47};48