Post

4119 Minimum Distance Between Three Equal Elements Ii

4119 Minimum Distance Between Three Equal Elements Ii

Minimum Distance Between Three Equal Elements II image

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
2
1 <= n == nums.length <= 105
1 <= nums[i] <= n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class Solution:
    def minimumDistance(self, nums: List[int]) -> int:
        # if i sort these on nums and then on index
        # then i slide a window of len 3
        # and calculate the dist
        if len(nums) < 3:
            return -1
        arr =  []
        for (i, k) in enumerate(nums):
            arr.append((k,i))

        arr.sort(key = lambda x : (x[0], x[1]))
        res = 1000000
        left =  0
        right = 2
        while(right < len(arr)):
            if arr[left][0] == arr[left + 1][0] and arr[left+1][0] == arr[right][0]:
                res = min(res, abs(arr[left][1] - arr[left + 1][1]) + abs(arr[left + 1][1] - arr[left + 2][1]) + abs(arr[left + 2][1] - arr[left][1]))
            right += 1
            left += 1
        return -1 if res == 1000000 else res






This post is licensed under CC BY 4.0 by the author.