Count Almost Equal Pairs I Problem
Description
LeetCode Problem 3265.
You are given an array nums consisting of positive integers.
We call two integers x and y in this problem almost equal if both integers can become equal after performing the following operation at most once:
- Choose either
xoryand swap any two digits within the chosen number.
Return the number of indices i and j in nums where i < j such that nums[i] and nums[j] are almost equal.
Note that it is allowed for an integer to have leading zeros after performing an operation.
Example 1:
Input: nums = [3,12,30,17,21]
Output: 2
Explanation:
The almost equal pairs of elements are:
- 3 and 30. By swapping 3 and 0 in 30, you get 3.
- 12 and 21. By swapping 1 and 2 in 12, you get 21.
Example 2:
Input: nums = [1,1,1,1,1]
Output: 10
Explanation:
Every two elements in the array are almost equal.
Example 3:
Input: nums = [123,231]
Output: 0
Explanation:
We cannot swap any two digits of 123 or 231 to reach the other.
Constraints:
2 <= nums.length <= 1001 <= nums[i] <= 10^6
Solution
Approach: Sorting + Enumeration
Go through the numbers one at a time. For each number x, build the set vis of every value reachable by swapping at most one pair of its digits (including x itself). Every earlier number that is in vis forms an almost-equal pair with x, so add its count from the hash map cnt, then record x in cnt.
Sorting first matters because a swap can create leading zeros: 100 becomes 1, but 1 can only be found if it was already counted. In ascending order the shorter number always comes first, so such pairs are not missed.
Complexity: O(n (log n + log3 M)) time and O(n + log2 M) space, where M is the largest value.
from collections import defaultdict
class Solution:
def countPairs(self, nums: List[int]) -> int:
nums.sort()
ans = 0
cnt = defaultdict(int)
for x in nums:
vis = {x}
s = list(str(x))
for j in range(len(s)):
for i in range(j):
s[i], s[j] = s[j], s[i]
vis.add(int("".join(s)))
s[i], s[j] = s[j], s[i]
ans += sum(cnt[x] for x in vis)
cnt[x] += 1
return ans