Show problems as
Classic problem #3741MediumArrayHash Table

Minimum Distance Between Three Equal Elements II

Real-world version: Tightest Triple of Matching Readings
Tracked in this browser only
Read Minimum Distance Between Three Equal Elements II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Readings are given as nums.

Find three positions holding the same reading and return the span from the first of them to the last, which is the difference of those two positions. Return -1 when no reading appears three times.

Examples

Example 1

Input
nums = [4, 2, 4, 7, 4, 2, 2, 7, 7, 2]
Output
4

The reading 2 sits at positions 1, 5, 6 and 9; the triple at 5, 6 and 9 spans 4, and the one at 1, 5 and 6 spans 5. The reading 4 sits at 0, 2 and 4, spanning 4, and the reading 7 at 3, 7 and 8, spanning 5. The tightest is 4.

Example 2

Input
nums = [1, 1, 1]
Output
2

The only triple runs from position 0 to position 2.

Example 3

Input
nums = [1, 2, 3, 4, 5]
Output
-1

No reading appears even twice, let alone three times.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= nums.length

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def minimum_distance(nums: list[int]) -> int:
Java
public int minimumDistance(int[] nums)