#3741
Minimum Distance Between Three Equal Elements II
MediumArrayHash 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)
Use a hash map to store indices of each number, allowing efficient retrieval of positions to calculate distances.
⚙️
Algorithm
3 steps- 1Step 1: Create a hash map to store indices of each number in the array.
- 2Step 2: For each number appearing at least 3 times, calculate the distance using the formula 2 * (max(i, j, k) - min(i, j, k)).
- 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 = 2 * (indices[-1] - indices[0])
10 min_dist = min(min_dist, dist)
11 return min_dist if min_dist != float('inf') else -1ℹ
Complexity note: The complexity is linear due to a single pass to build the index map and another pass to calculate distances.
- 1A good tuple requires at least three occurrences of the same element.
- 2Distance can be simplified to focus on the maximum and minimum indices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.