3761. Minimum Absolute Distance Between Mirror Pairs
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
Solution 1: Hash Table
We can use a hash table \(\textit{pos}\) to record the last occurrence position of each reversed number.
We first initialize the answer \(\textit{ans} = n + 1\), where \(n\) is the length of the array \(\textit{nums}\).
Next, we iterate through the array \(\textit{nums}\). For each index \(i\) and its corresponding number \(x = \textit{nums}[i]\), if the key \(x\) exists in \(\textit{pos}\), it means there exists an index \(j\) such that \(\textit{nums}[j]\) reversed equals \(x\). In this case, we update the answer to \(\min(\textit{ans}, i - \textit{pos}[x])\). Then, we update \(\textit{pos}[\text{reverse}(x)]\) to \(i\). Continue this process until we finish iterating through the entire array.
Finally, if the answer \(\textit{ans}\) is still equal to \(n + 1\), it means no mirror pair exists, and we return \(-1\); otherwise, we return the answer \(\textit{ans}\).
The time complexity is \(O(n \times \log M)\), where \(n\) is the length of the array \(\textit{nums}\), and \(M\) is the maximum value in the array. The space complexity is \(O(n)\), which is used to store the hash table \(\textit{pos}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |