leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 8dd4c7adb21c48504df2ab1cc5847d311616d10d
parent 240779899ce23625ea9441dd6b63eabbfdcff308
Author: Jack Sangdahl <jack@pngu.org>
Date:   Thu,  9 Apr 2026 21:54:31 -0600

3740. minimum distance between three equal elements 1

Diffstat:
Amin_dist_betw_3eq_elem.c | 39+++++++++++++++++++++++++++++++++++++++
Amin_dist_betw_3eq_elem.py | 32++++++++++++++++++++++++++++++++
2 files changed, 71 insertions(+), 0 deletions(-)

diff --git a/min_dist_betw_3eq_elem.c b/min_dist_betw_3eq_elem.c @@ -0,0 +1,39 @@ +// 3740. Minimum Distance Between Three Equal Elements I +#include "leetcode.h" + +/* + * 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 - k)', 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. + */ + +int minimumDistance(int *nums, int numsSize) { + int ans = INT_MAX; + for (int i = 0; i < numsSize; i++) + for (int j = i + 1; j < numsSize - 1; j++) { + if (nums[j] != nums[i]) + continue; + for (int k = j + 1; k < numsSize; k++) { + if (nums[j] == nums[k]) + ans = fmin(ans, (j - i) + (k - j) + (k - i)); + } + } + if (ans == INT_MAX) + return -1; + return ans; +} + +int main() { + int n1[] = {1, 2, 1, 1, 3}, n2[] = {1, 1, 2, 3, 2, 1, 2}, n3[] = {1}; + int r1 = minimumDistance(n1, ARRAY_SIZE(n1)); + int r2 = minimumDistance(n2, ARRAY_SIZE(n2)); + int r3 = minimumDistance(n3, ARRAY_SIZE(n3)); + printf("%d\n", r1); + assert(r1 == 6); + printf("%d\n", r2); + assert(r2 == 8); + printf("%d\n", r3); + assert(r3 == -1); +} diff --git a/min_dist_betw_3eq_elem.py b/min_dist_betw_3eq_elem.py @@ -0,0 +1,32 @@ +# 3740. Minimum Distance Between Three Equal Elements I +from typing import List + +""" +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 - k)', 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. +""" + + +class Solution: + def minimumDistance(self, nums: List[int]) -> int: + n = len(nums) + prev = [0] * n + res = 300 + for i in range(n): + val, pos = nums[i] - 1, i + 1 + pack = prev[val] + old, cur = pack & 255, pack >> 8 + prev[val] = cur | (pos << 8) + if old: + res = min(res, (pos - old) << 1) + return -(res == 300) | res + + +if __name__ == "__main__": + obj = Solution() + print(obj.minimumDistance(nums=[1, 2, 1, 1, 3])) + print(obj.minimumDistance(nums=[1, 1, 2, 3, 2, 1, 2])) + print(obj.minimumDistance(nums=[1]))