Minimum Distance to the Target Element - Problem
Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized.
Note: abs(x) is the absolute value of x.
Return abs(i - start).
It is guaranteed that target exists in nums.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,4,5], target = 5, start = 3
›
Output:
1
💡 Note:
Target 5 is at index 4. Distance from start=3 is |4-3| = 1
Example 2 — Multiple Targets
$
Input:
nums = [1], target = 1, start = 0
›
Output:
0
💡 Note:
Target 1 is at index 0, same as start. Distance is |0-0| = 0
Example 3 — Choose Closer Target
$
Input:
nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
›
Output:
0
💡 Note:
Target 1 appears everywhere, including at start position. Minimum distance is 0
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 104
- 0 ≤ start < nums.length
- target is in nums
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with target value and start position
2
Process
Find all occurrences of target and calculate distances
3
Output
Return the minimum distance found
Key Takeaway
🎯 Key Insight: We only need one pass through the array to find all target occurrences and track the minimum distance to start position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code