- 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
- 36 lines of Python from the credited upstream file 3267.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 1 loop block 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 3 def countPairs(self, nums: list[int]) -> int:4 ans = 05 count = collections.Counter()6 maxLen = len(str(max(nums)))7 8 for num in nums:9 digits = list(str(num).zfill(maxLen))10 for swap in self._getSwaps(digits):11 ans += count[swap]12 count[num] += 113 14 return ans15 16 def _getSwaps(self, digits: str) -> set[int]:17 """Returns all possible numbers after 1 or 2 swaps."""18 n = len(digits)19 swaps = set([int(''.join(digits))])20 21 22 for i, j in itertools.combinations(range(n), 2):23 newDigits = digits[:]24 newDigits[i], newDigits[j] = newDigits[j], newDigits[i]25 swaps.add(int(''.join(newDigits)))26 27 28 for (i1, j1), (i2, j2) in itertools.combinations(29 itertools.combinations(range(n), 2), 2):30 newDigits = digits[:]31 newDigits[i1], newDigits[j1] = newDigits[j1], newDigits[i1]32 newDigits[i2], newDigits[j2] = newDigits[j2], newDigits[i2]33 swaps.add(int(''.join(newDigits)))34 35 return swaps36