Description
You are given an integer array nums.
A mirror pair is a pair of indices (i, j) such that:
0 <= i < j < nums.length, andreverse(nums[i]) == nums[j], wherereverse(x)denotes the integer formed by reversing the digits ofx. Leading zeros are omitted after reversing, for examplereverse(120) = 21.
Return the minimum absolute distance between the indices of any mirror pair. The absolute distance between indices i and j is abs(i - j).
If no mirror pair exists, return -1.
Example 1:
Input: nums = [12,21,45,33,54]
Output: 1
Explanation:
The mirror pairs are:
- (0, 1) since
reverse(nums[0]) = reverse(12) = 21 = nums[1], giving an absolute distanceabs(0 - 1) = 1. - (2, 4) since
reverse(nums[2]) = reverse(45) = 54 = nums[4], giving an absolute distanceabs(2 - 4) = 2.
The minimum absolute distance among all pairs is 1.
Example 2:
Input: nums = [120,21]
Output: 1
Explanation:
There is only one mirror pair (0, 1) since reverse(nums[0]) = reverse(120) = 21 = nums[1].
The minimum absolute distance is 1.
Example 3:
Input: nums = [21,120]
Output: -1
Explanation:
There are no mirror pairs in the array.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109
Solutions
This function finds the minimum distance between two indices in an array where one number is the digit reverse of another (e.g., 123 and 321). It uses a Map to track the reversed versions of previously seen numbers along with their positions; as it iterates through the array, for each number it checks if that number was already seen as the reverse of an earlier number, and if so, it records the distance between their positions using Math.min(). The helper function reverseNum extracts individual digits using modulo and division to flip a number's digit order. If no mirror pairs are found, the function returns -1; otherwise, it returns the smallest distance between any such pair.
/**
* @param {number[]} nums
* @return {number}
*/
var minMirrorPairDistance = function(nums) {
const map = new Map();
let min = Infinity;
for (let i = 0; i < nums.length; i++) {
const pos = map.get(nums[i]) ?? -1;
if (pos > -1) {
min = Math.min(min, i - pos);
}
const reverse = reverseNum(nums[i]);
map.set(reverse, i);
}
if (min === Infinity) {
return -1;
}
return min;
};
const reverseNum = (num) => {
let res = 0;
while (num > 0) {
res = res * 10 + (num % 10);
num = Math.floor(num / 10);
}
return res;
};