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
Visualization
Time & Space Complexity
n iterations, each generating O(dยฒ) variations with O(dยฒ) additional variations from 2-swaps, where d is number of digits
Hash map stores all variations for all numbers processed
Constraints
- 1 โค nums.length โค 3000
- 1 โค nums[i] โค 107
- At most 2 swap operations allowed per number
- Leading zeros are allowed after swapping