commit 5c1d264f5468d0bb020c0280135b34c31339ec66
parent 7f780ea828792ef5cf2496db435c9b8fca73370b
Author: Jack Sangdahl <jack@pngu.org>
Date: Sun, 12 Apr 2026 21:28:01 -0600
1848. minimum distance to the target element
Diffstat:
2 files changed, 52 insertions(+), 0 deletions(-)
diff --git a/min_dist_target_elem.c b/min_dist_target_elem.c
@@ -0,0 +1,32 @@
+// 1848. Minimum Distance to the Target Element
+#include "leetcode.h"
+
+/*
+ * given an integer array 'nums' and two integers 'target' and 'start', find an
+ * index 'i' such that 'nums[i] == target' and 'abs(i - start)' is minimised.
+ * note that 'abs(x)' is the absolute value of 'x'. return 'abs(i - start)'. it
+ * is guaranteed that 'target' exists in 'nums'.
+ */
+
+int getMinDistance(int *nums, int numsSize, int target, int start) {
+ int ans = INT_MAX;
+ for (int i = 0; i < numsSize; i++)
+ if (nums[i] == target)
+ ans = fmin(ans, abs(i - start));
+ return ans;
+}
+
+int main() {
+ int n1[] = {1, 2, 3, 4, 5};
+ int n2[] = {1};
+ int n3[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
+ int r1 = getMinDistance(n1, ARRAY_SIZE(n1), 5, 3);
+ int r2 = getMinDistance(n2, ARRAY_SIZE(n2), 1, 0);
+ int r3 = getMinDistance(n3, ARRAY_SIZE(n3), 1, 0);
+ printf("%d\n", r1);
+ assert(r1 == 1);
+ printf("%d\n", r2);
+ assert(r2 == 0);
+ printf("%d\n", r3);
+ assert(r3 == 0);
+}
diff --git a/min_dist_target_elem.py b/min_dist_target_elem.py
@@ -0,0 +1,20 @@
+# 1848. Minimum Distance to the Target Element
+
+"""
+given an integer array 'nums' and two integers 'target' and 'start', find an
+index 'i' such that 'nums[i] == target' and 'abs(i - start)' is minimised.
+note that 'abs(x)' is the absolute value of 'x'. return 'abs(i - start)'. it
+is guaranteed that 'target' exists in 'nums'.
+"""
+
+
+class Solution:
+ def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
+ return min(abs(i - start) for i, j in enumerate(nums) if j == target)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.getMinDistance(nums=[1, 2, 3, 4, 5], target=5, start=3))
+ print(obj.getMinDistance(nums=[1], target=1, start=0))
+ print(obj.getMinDistance(nums=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], target=1, start=0))