DatabricksOA #26
Count Distinct Pairs
Estimated MediumJudge-ready
You are given an array of positive integers. An index pair i<j is valid if, after swapping the digits at two positions of the decimal representation of fruits[j] zero times or once, the resulting integer equals fruits[i]. Count the valid index pairs. Zero swaps are allowed, so equal values also count. The digit string after swapping is interpreted as an ordinary decimal integer; leading zeros are not kept.
Input
The first line contains an integer n (1≤n≤10000); the second line contains n positive integers fruits[i] (1≤fruits[i]≤10^9).
Output
Output the number of valid index pairs.
Example 1
Input:
7
1 23 156 1650 651 165 32
Output:
3
Example 2
Input:
3
123 321 123
Output:
3
Example 3
Input:
4
1 1000 10 100
Output:
4
Example notes
For each right-end value, enumerate the integers reachable with zero or one swap, and look up how many times each occurred earlier. Do not treat all numbers with the same digits as mutually reachable; one swap can change only two positions.
Editorial
Loading solution…