Count Almost Equal Pairs II - Problem
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 x or y and 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.
Input & Output
Example 1 — Basic Almost Equal
$
Input:
nums = [3,12,30,17,21]
›
Output:
2
💡 Note:
The almost equal pairs are (12,21) - swap 1↔2 in 12 to get 21, and (30,3) - 30→03→3 with leading zero allowed
Example 2 — No Valid Pairs
$
Input:
nums = [1,1,1,1,1]
›
Output:
10
💡 Note:
All numbers are identical, so all C(5,2) = 10 pairs are almost equal (0 swaps needed)
Example 3 — Complex Swapping
$
Input:
nums = [123,321]
›
Output:
1
💡 Note:
Can make 123→321 with 2 swaps: 123→321 (swap positions 0↔2), so this pair is almost equal
Constraints
- 1 ≤ nums.length ≤ 3000
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array of positive integers to analyze
2
Check Pairs
For each pair, determine if almost equal with ≤2 swaps
3
Count Result
Return total number of valid almost equal pairs
Key Takeaway
🎯 Key Insight: Two numbers are almost equal if they have identical digit frequencies and differ in at most 4 positions (resolvable with 2 swaps)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code