Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
The small array permits enumerating every triple of distinct indices. Requiring increasing indices avoids counting the same three positions in different orders. A triple contributes only when all three stored values are equal.
Approach
Use three nested loops with i < j < k. For each triple, compare its values. When they match, calculate abs(i - j) + abs(j - k) + abs(i - k) and retain the smallest distance.
The increasing order means this expression equals 2 * (k - i), though the supplied code evaluates the original pairwise-distance formula directly. Initialize the best distance to infinity and return -1 if no matching triple was found. Every eligible triple is examined once, so the minimum is exhaustive rather than dependent on a greedy choice.
class Solution:
def minimumDistance(self, nums: List[int]) -> int:
n = len(nums)
res = inf
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if nums[i] == nums[j] and nums[j] == nums[k]:
res = min(res, abs(i - j) + abs(j - k) + abs(i - k))
return res if res != inf else -1Complexity analysis
Let n = nums.length. Time: O(n^3). Auxiliary space: O(1).
