Minimum Absolute Distance Between Mirror Pairs Problem
Description
LeetCode Problem 3761.
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 distance abs(0 - 1) = 1.
- (2, 4) since reverse(nums[2]) = reverse(45) = 54 = nums[4], giving an absolute distance abs(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 <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Hash Table
Scan the array from left to right and keep a hash map pos that maps reverse(nums[j]) to the latest index j seen so far. When we reach index i with value x, a mirror pair (j, i) exists exactly when reverse(nums[j]) == x, which is the same as x being a key in pos. In that case i - pos[x] is the closest such distance ending at i, so update the answer with it. Then store pos[reverse(x)] = i.
Storing only the latest index per key is enough because a later index always gives a smaller distance. If no pair was found, return -1.
Complexity: O(n log M) time, where M is the largest value (reversing a number takes one step per digit), and O(n) space.
from math import inf
class Solution:
def minMirrorPairDistance(self, nums: List[int]) -> int:
def reverse(x: int) -> int:
y = 0
while x:
v = x % 10
y = y * 10 + v
x //= 10
return y
pos = {}
ans = inf
for i, x in enumerate(nums):
if x in pos:
ans = min(ans, i - pos[x])
pos[reverse(x)] = i
return -1 if ans == inf else ans