Intuition
Try every ordered pair (i, j) with i < j, reverse nums[i] and check whether it equals nums[j]. Track the smallest j - i.
Explanation
Approach
- Define
rev(x)= integer formed by reversing the decimal digits ofx(leading zeros dropped). - For each
ifrom0ton - 2:- For each
jfromi + 1ton - 1:- If
rev(nums[i]) == nums[j], recordj - ias a candidate.
- If
- For each
- Return the minimum, or
-1if none found.
Complexity
- Time:
O(n² · L)whereLis the number of digits. Withn = 10^5this TLEs. - Space:
O(L)for the reversal.
Implementation
import java.util.*;
class Solution {
public int minMirrorPairDistance(int[] nums) {
int n = nums.length;
int best = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int rev = reverse(nums[i]);
for (int j = i + 1; j < n; j++) {
if (nums[j] == rev) {
best = Math.min(best, j - i);
break;
}
}
}
return best == Integer.MAX_VALUE ? -1 : best;
}
private int reverse(int x) {
int rev = 0;
while (x > 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
return rev;
}
}