Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
For an earlier number, store the value its digit reversal would need to match later. When the current number matches such a key, the most recent earlier index gives the shortest distance. The direction matters because reversing an integer discards leading zeros.
Approach
Scan left to right with a map from reversed values to their latest source indices. Before inserting the current number, look it up as a key. If present, use the difference between the current index and that stored index to update the answer. Compute its reversal and store the current index under that value. Python reverses its decimal string and parses the result; JavaScript constructs the reversal with remainder and integer division by ten.
Looking up before insertion prevents pairing an element with itself. Keeping only the latest index is sufficient because every future matching index is closer to it than to any earlier source with the same reversal. Return -1 if no match is found. This correctly treats 120 followed by 21 as directional reversal, without assuming the reverse relation also holds.
class Solution:
def minMirrorPairDistance(self, nums: List[int]) -> int:
rev = {}
res = inf
for i, n in enumerate(nums):
if n in rev: res = min(res, i - rev[n])
r = int(str(n)[::-1])
rev[r] = i
return res if res != inf else -1Complexity analysis
Let n = nums.length and D be the maximum digit count. Reversing each number and performing hash-map lookups takes O(nD) time, which is O(n) under the stated integer bound, and O(n) auxiliary space.
