Minimum Distance Between Three Equal Elements I Problem
Description
LeetCode Problem 3740.
You are given an integer array nums.
A tuple (i, j, k) of 3 distinct indices is good if nums[i] == nums[j] == nums[k].
The distance of a good tuple is abs(i - j) + abs(j - k) + abs(k - i), where abs(x) denotes the absolute value of x.
Return an integer denoting the minimum possible distance of a good tuple. If no good tuples exist, return -1.
Example 1:
Input: nums = [1,2,1,1,3]
Output: 6
Explanation:
The minimum distance is achieved by the good tuple (0, 2, 3).
(0, 2, 3) is a good tuple because nums[0] == nums[2] == nums[3] == 1. Its distance is abs(0 - 2) + abs(2 - 3) + abs(3 - 0) = 2 + 1 + 3 = 6.
Example 2:
Input: nums = [1,1,2,3,2,1,2]
Output: 8
Explanation:
The minimum distance is achieved by the good tuple (2, 4, 6).
(2, 4, 6) is a good tuple because nums[2] == nums[4] == nums[6] == 2. Its distance is abs(2 - 4) + abs(4 - 6) + abs(6 - 2) = 2 + 2 + 4 = 8.
Example 3:
Input: nums = [1]
Output: -1
Explanation:
There are no good tuples. Therefore, the answer is -1.
Constraints:
1 <= n == nums.length <= 1001 <= nums[i] <= n
Solution
Approach: Group indices by value
For a good tuple with sorted indices i < j < k, the distance is 2 * (k - i), so j does not matter. For each value, collect its indices in increasing order; the best tuple among them uses three consecutive occurrences, since that makes k - i smallest.
So for every window ls[h], ls[h+1], ls[h+2] of a value's index list, take 2 * (ls[h+2] - ls[h]), and return the minimum, or -1 if no value occurs three times.
Complexity: time O(n), space O(n).
from collections import defaultdict
from math import inf
class Solution:
def minimumDistance(self, nums: List[int]) -> int:
g = defaultdict(list)
for i, x in enumerate(nums):
g[x].append(i)
ans = inf
for ls in g.values():
for h in range(len(ls) - 2):
i, k = ls[h], ls[h + 2]
ans = min(ans, (k - i) * 2)
return -1 if ans == inf else ans