Count Almost Equal Pairs I - Problem
You are given an array nums of positive integers. Your task is to count pairs of numbers that are "almost equal" - meaning they can become identical with at most one strategic digit swap!
What makes two numbers "almost equal"?
- They are already identical, OR
- You can pick either number and swap any two of its digits to make them equal
Goal: Return the number of valid pairs (i, j) where i < j and nums[i] and nums[j] are almost equal.
Example: Numbers 123 and 132 are almost equal because swapping digits 2 and 3 in 132 gives us 123.
Note: Leading zeros are allowed after swapping (e.g., 102 can become 021).
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 and 21: swap digits in 12 to get 21. For 30 and 3: 30 becomes 03 which equals 3 when leading zeros are ignored.
example_2.py — No Pairs
$
Input:
nums = [1,1,1,1,1]
›
Output:
10
💡 Note:
All numbers are identical, so every pair (i,j) where i < j is almost equal. With 5 identical numbers, we have C(5,2) = 10 pairs.
example_3.py — Complex Swaps
$
Input:
nums = [123,231,111,112]
›
Output:
4
💡 Note:
Pairs: (123,231) - swap 1,3 in 123 to get 321, then 2,1 to get 231. Actually, we can get 132, 213, 321 from 123 by single swaps. 231 can be made from 123 by swapping positions 0 and 1.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Patterns
For each lock, list all combinations it can achieve with one swap
2
Group Compatible Locks
Locks that can achieve the same combinations are almost equal
3
Count Pairs
Within each group of n compatible locks, there are n×(n-1)/2 pairs
Key Takeaway
🎯 Key Insight: Instead of comparing every pair directly, we group numbers by their 'reachable patterns' using hash maps, turning an O(n² × d³) problem into O(n × d²)!
Time & Space Complexity
Time Complexity
O(n × d²)
For each of n numbers, we generate O(d²) possible swaps where d is the number of digits
✓ Linear Growth
Space Complexity
O(n × d²)
Hash map stores all possible patterns for all numbers
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 100
- 1 ≤ nums[i] ≤ 106
- Leading zeros are allowed after swapping
- Numbers can have different lengths and still be almost equal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code