#3761
Medium Algorithms Minimum absolute distance between mirror pairs
Array Hash Table Math
44.3% acceptance
Feb 25, 2026
77
3
You are given an integer array nums.
A mirror pair is a pair of indices (i, j) such that:
0 <= i < j < nums.length, and
reverse(nums[i]) == nums[j], where reverse(x) denotes the integer formed by reversing the digits of x. Leading zeros are omitted after reversing, for example reverse(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.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn min_mirror_pair_distance(nums: Vec<i32>) -> i32 {
fn reverse_num(mut n: i32) -> i32 {
let mut r = 0i32;
while n > 0 { r = r * 10 + n % 10; n /= 10; }
r
}
use std::collections::HashMap;
// For pair (i,j) with i<j: reverse(nums[i]) == nums[j]
// For each i, store reverse(nums[i]) -> latest index i
// Then for index j, look up nums[j] in map to find latest i < j with reverse(nums[i])==nums[j]
let mut rev_map: HashMap<i32, usize> = HashMap::new();
let mut ans = i32::MAX;
for (j, &v) in nums.iter().enumerate() {
if let Some(&i) = rev_map.get(&v) {
ans = ans.min((j - i) as i32);
}
rev_map.insert(reverse_num(v), j);
}
if ans == i32::MAX { -1 } else { ans }
}
}