Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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] <= nProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[1,2,1,1,3]
[1,1,2,3,2,1,2]
[1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3740: Minimum Distance Between Three Equal Elements I
class Solution {
public int minimumDistance(int[] nums) {
int n = nums.length;
Map<Integer, List<Integer>> g = new HashMap<>();
for (int i = 0; i < n; ++i) {
g.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i);
}
final int inf = 1 << 30;
int ans = inf;
for (var ls : g.values()) {
int m = ls.size();
for (int h = 0; h < m - 2; ++h) {
int i = ls.get(h);
int k = ls.get(h + 2);
int t = (k - i) * 2;
ans = Math.min(ans, t);
}
}
return ans == inf ? -1 : ans;
}
}
// Accepted solution for LeetCode #3740: Minimum Distance Between Three Equal Elements I
func minimumDistance(nums []int) int {
g := make(map[int][]int)
for i, x := range nums {
g[x] = append(g[x], i)
}
inf := 1 << 30
ans := inf
for _, ls := range g {
m := len(ls)
for h := 0; h < m-2; h++ {
i := ls[h]
k := ls[h+2]
t := (k - i) * 2
ans = min(ans, t)
}
}
if ans == inf {
return -1
}
return ans
}
# Accepted solution for LeetCode #3740: Minimum Distance Between Three Equal Elements I
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
// Accepted solution for LeetCode #3740: Minimum Distance Between Three Equal Elements I
fn minimum_distance(nums: Vec<i32>) -> i32 {
let mut positions = vec![vec![]; nums.len() + 1];
for (i, n) in nums.into_iter().enumerate() {
positions[n as usize].push(i);
}
let mut ret = i32::MAX;
for p in positions {
let len = p.len();
for i in 0..len {
for j in (i + 1)..len {
for k in (j + 1)..len {
ret = std::cmp::min(ret, (p[j] - p[i] + p[k] - p[i] + p[k] - p[j]) as i32);
}
}
}
}
if ret == i32::MAX {
-1
} else {
ret
}
}
fn main() {
let nums = vec![1, 2, 1, 1, 3];
let ret = minimum_distance(nums);
println!("ret={ret}");
}
#[test]
fn test() {
{
let nums = vec![1, 2, 1, 1, 3];
let ret = minimum_distance(nums);
assert_eq!(ret, 6);
}
{
let nums = vec![1, 1, 2, 3, 2, 1, 2];
let ret = minimum_distance(nums);
assert_eq!(ret, 8);
}
{
let nums = vec![1];
let ret = minimum_distance(nums);
assert_eq!(ret, -1);
}
}
// Accepted solution for LeetCode #3740: Minimum Distance Between Three Equal Elements I
function minimumDistance(nums: number[]): number {
const n = nums.length;
const g = new Map<number, number[]>();
for (let i = 0; i < n; i++) {
if (!g.has(nums[i])) {
g.set(nums[i], []);
}
g.get(nums[i])!.push(i);
}
const inf = 1 << 30;
let ans = inf;
for (const ls of g.values()) {
const m = ls.length;
for (let h = 0; h < m - 2; h++) {
const i = ls[h];
const k = ls[h + 2];
const t = (k - i) * 2;
ans = Math.min(ans, t);
}
}
return ans === inf ? -1 : ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.