3534. Count Almost Equal Pairs I
My accepted Python solution to LeetCode problem 3534, Count Almost Equal Pairs I, running in 3161ms.
- Difficulty: Medium
- Python
- Runtime 3161ms
- Memory 17.4MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 3161ms, memory 17.4MB, accepted 2025-12-29.
class Solution:
def countPairs(self, nums: List[int]) -> int:
def can_be_equal(a: int, b: int) -> bool:
# Check if a and b can become equal with at most one swap in either number
if a == b:
return True
# Convert to strings with same length (pad with leading zeros)
s1 = str(a)
s2 = str(b)
# Pad to same length
max_len = max(len(s1), len(s2))
s1 = s1.zfill(max_len)
s2 = s2.zfill(max_len)
# Find positions where they differ
diffs = []
for i in range(max_len):
if s1[i] != s2[i]:
diffs.append(i)
if len(diffs) == 0:
return True
elif len(diffs) == 2:
# Try swapping in s1
i, j = diffs
s1_list = list(s1)
s1_list[i], s1_list[j] = s1_list[j], s1_list[i]
if ''.join(s1_list) == s2:
return True
# Try swapping in s2
s2_list = list(s2)
s2_list[i], s2_list[j] = s2_list[j], s2_list[i]
if ''.join(s2_list) == s1:
return True
# Also check if swapping any two digits makes them equal
# This is for cases where diffs > 2 but a swap within one number can still work
# Generate all possible results of swapping two digits in a
def get_all_swaps(s):
results = {s} # Include original
n = len(s)
for i in range(n):
for j in range(i + 1, n):
lst = list(s)
lst[i], lst[j] = lst[j], lst[i]
results.add(''.join(lst))
return results
swaps_a = get_all_swaps(s1)
swaps_b = get_all_swaps(s2)
# Check if any swap of a equals b or any swap of b equals a
if s2 in swaps_a or s1 in swaps_b:
return True
return False
count = 0
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if can_be_equal(nums[i], nums[j]):
count += 1
return count