Count Almost Equal Pairs II - Problem
You're given an array of positive integers, and your task is to find pairs of numbers that are "almost equal" - meaning they can become identical through digit swapping operations.
Two integers x and y are considered almost equal if you can make them identical by performing at most 2 swap operations. In each operation, you can:
- Choose either
xory - Swap any two digits within the chosen number
For example, 1234 and 3412 are almost equal because:
- Swap digits at positions 0,2 in 1234 โ 3214
- Swap digits at positions 1,3 in 3214 โ 3412
Goal: Count all pairs (i, j) where i < j and nums[i] and nums[j] are almost equal.
Note: Leading zeros are allowed after swapping operations.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [3, 12, 30, 17, 21]
โบ
Output:
2
๐ก Note:
The almost equal pairs are (12, 21) and (30, 3). For (12, 21): swap positions 0,1 in 12 โ 21. For (30, 3): swap positions 0,1 in 30 โ 03 = 3.
example_2.py โ Multiple Swaps
$
Input:
nums = [1, 1, 1, 1, 1]
โบ
Output:
10
๐ก Note:
All identical numbers are almost equal (requiring 0 swaps). With 5 identical numbers, we have C(5,2) = 10 pairs.
example_3.py โ Complex Case
$
Input:
nums = [1234, 2143, 1324, 4321]
โบ
Output:
4
๐ก Note:
Multiple numbers can be transformed into each other with at most 2 swaps. For example, 1234 โ 1324 (one swap), 1234 โ 2143 (two swaps), etc.
Constraints
- 1 โค nums.length โค 3000
- 1 โค nums[i] โค 107
- At most 2 swap operations allowed per number
- Leading zeros are allowed after swapping
Visualization
Tap to expand
Understanding the Visualization
1
Generate Variations
For each number, create all possible arrangements with 0, 1, or 2 swaps
2
Hash Storage
Store each variation in a hash map with its frequency count
3
Count Matches
For new numbers, check if any of their variations exist in the hash map
4
Accumulate Pairs
Sum up all the matching counts to get total almost equal pairs
Key Takeaway
๐ฏ Key Insight: Instead of comparing every pair directly (O(nยฒ)), we transform the problem into a grouping problem where numbers that can reach the same variations are automatically paired together through hash map lookups.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code