#3761
Minimum Absolute Distance Between Mirror Pairs
MediumArrayHash TableMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a hash map to store the most recent index of each reversed number allows us to find mirror pairs efficiently in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a hash map to store the most recent index of reversed numbers.
- 2Step 2: Iterate through nums, reverse each number, and check if it exists in the map.
- 3Step 3: If it exists, calculate the distance and update the minimum if it's smaller.
solution.py9 lines
1def minAbsDist(nums):
2 index_map = {}
3 min_dist = float('inf')
4 for i, num in enumerate(nums):
5 rev_num = int(str(num)[::-1])
6 if rev_num in index_map:
7 min_dist = min(min_dist, i - index_map[rev_num])
8 index_map[num] = i
9 return min_dist if min_dist != float('inf') else -1ℹ
Complexity note: We traverse the array once and use a hash map for storage, leading to O(n) time and space.
- 1Mirror pairs depend on reversing numbers.
- 2Using a hash map allows efficient lookups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.