Count Almost Equal Pairs II Problem
Description
LeetCode Problem 3267.
Attention: In this version, the number of operations that can be performed, has been increased to twice.
You are given an array nums consisting of positive integers.
We call two integers x and y almost equal if both integers can become equal after performing the following operation at most twice:
- 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 = [1023,2310,2130,213]
Output: 4
Explanation:
The almost equal pairs of elements are:
- 1023 and 2310. By swapping the digits 1 and 2, and then the digits 0 and 3 in 1023, you get 2310.
- 1023 and 213. By swapping the digits 1 and 0, and then the digits 1 and 2 in 1023, you get 0213, which is 213.
- 2310 and 213. By swapping the digits 2 and 0, and then the digits 3 and 2 in 2310, you get 0213, which is 213.
- 2310 and 2130. By swapping the digits 3 and 1 in 2310, you get 2130.
Example 2:
Input: nums = [1,10,100]
Output: 3
Explanation:
The almost equal pairs of elements are:
- 1 and 10. By swapping the digits 1 and 0 in 10, you get 01 which is 1.
- 1 and 100. By swapping the second 0 with the digit 1 in 100, you get 001, which is 1.
- 10 and 100. By swapping the first 0 with the digit 1 in 100, you get 010, which is 10.
Constraints:
2 <= nums.length <= 50001 <= nums[i] < 10^7
Solution
Approach: Sorting + Enumeration
For each number build the set vis of values reachable with at most two swaps: first every single swap of two digits, then, from each of those, every swap of a different pair of positions. Count how many earlier numbers are in vis, then record the current number.
Sort the array first. Swaps can create leading zeros (100 becomes 1), and sorting guarantees the shorter number is processed earlier, so no pair is missed.
Complexity: O(n (log n + log5 M)) time and O(n + log4 M) space.
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))
m = len(s)
for j in range(m):
for i in range(j):
s[i], s[j] = s[j], s[i]
vis.add(int("".join(s)))
for q in range(i + 1, m):
for p in range(i + 1, q):
s[p], s[q] = s[q], s[p]
vis.add(int("".join(s)))
s[p], s[q] = s[q], s[p]
s[i], s[j] = s[j], s[i]
ans += sum(cnt[x] for x in vis)
cnt[x] += 1
return ans