Problem Description
Given an array of positive integers, count the number of pairs (i, j) with i < j such that the two numbers are "almost equal." Two integers are considered almost equal if, by performing at most one swap of any two digits in one of the numbers, they can be transformed to be equal. Leading zeros after the swap are allowed.
Key Insights
- For each number, generate all possible values after performing at most one swap (including keeping the number unchanged).
- Compare each pair (i, j) by checking if there is an intersection between the sets of possible transformed values for the two numbers.
- The maximum number of digits is small (since nums[i] <= 10^6), making it efficient to compute all swap outcomes.
- Use a brute-force pairwise comparison as the array length is limited (n <= 100).
Space and Time Complexity
Time Complexity: O(n^2 * d^2) where n is the number of numbers and d is the number of digits (d is small, at most 7).
Space Complexity: O(n * m) where m is the number of unique outcomes for each number (m is limited by d^2).
Solution
We approach the problem by precomputing a set of possible numbers for each integer after performing at most one digit-swap (including the original number in the set). For every pair (i, j), we check if the two sets have any common element, meaning one number in one set equals one number in the other set, making them "almost equal." Due to small input sizes, iterating with nested loops and using set intersection is efficient.
Data structures used:
- A list to store the generated sets for each number.
- A set for each number to avoid duplicate values from swaps.
Algorithm steps:
- Convert the number to its string representation to access individual digits.
- Generate the candidate set by swapping every pair of digits (only if the swap produces a new configuration) while also including the original number.
- Iterate through all pairs (i, j) and check set intersections.
- Count pairs that share a common element.