#3740
Minimum Distance Between Three Equal Elements I
EasyArrayHash TableHash 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)
We can use a hash map to store the indices of each element. This allows us to quickly find the distances between indices of the same element without checking all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Create a hash map to store lists of indices for each unique element in nums.
- 2Step 2: For each element with at least three indices, calculate the distance using the first three indices.
- 3Step 3: Return the minimum distance found or -1 if no valid tuples exist.
solution.py11 lines
1def minDistance(nums):
2 from collections import defaultdict
3 index_map = defaultdict(list)
4 for i, num in enumerate(nums):
5 index_map[num].append(i)
6 min_dist = float('inf')
7 for indices in index_map.values():
8 if len(indices) >= 3:
9 dist = abs(indices[0] - indices[1]) + abs(indices[1] - indices[2]) + abs(indices[2] - indices[0])
10 min_dist = min(min_dist, dist)
11 return min_dist if min_dist != float('inf') else -1ℹ
Complexity note: We traverse the array once to build the index map and then check each unique element's indices, leading to linear time complexity.
- 1Using a hash map reduces the number of checks needed.
- 2Focusing on indices of repeated elements allows for quick distance calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.