[LeetCode] Minimum Absolute Distance Between Mirror Pairs

3761. Minimum Absolute Distance Between Mirror Pairs

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int rev(int x) {
string s = to_string(x);
int res = 0;
while(s.length()) {
res = res * 10 + s.back() - '0';
s.pop_back();
}
return res;
}
public:
int minMirrorPairDistance(vector<int>& nums) {
unordered_map<int,int> at;
int res = INT_MAX;
for(int i = 0; i < nums.size(); i++) {
if(at.count(nums[i])) res = min(res, i - at[nums[i]]);
at[rev(nums[i])] = i;
}
return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-absolute-distance-between-mirror-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.