Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 11, 2026 17:32
Show Gist options
  • Select an option

  • Save tatsuyax25/cf362ae131c83c9c2dc10ff942a9914b to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/cf362ae131c83c9c2dc10ff942a9914b to your computer and use it in GitHub Desktop.
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 in
/**
* @param {number[]} nums
* @return {number}
*/
var minimumDistance = function(nums) {
const lastTwo = new Map(); // value -> [prevPrev, prev]
let ans = Infinity;
for (let i = 0; i < nums.length; i++) {
const v = nums[i];
if (!lastTwo.has(v)) {
lastTwo.set(v, [i]); // first occurrence
continue;
}
const arr = lastTwo.get(v);
if (arr.length === 1) {
// second occurrence
arr.push(i);
continue;
}
// arr.length === 2 → we have a triple window
const [a, b] = arr; // previous two
const c = i; // current
ans = Math.min(ans, 2 * (c - a));
// slide window:drop oldest, keep newest two
lastTwo.set(v, [b, c]);
}
return ans === Infinity ? -1 : ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment