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
Minimum Distance to Target ElementInput Array:1343501234start=2Target = 3Start = 2Target found at indices:• Index 1: distance |1-2| = 1• Index 3: distance |3-2| = 1Minimum Distance = 1
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
Asked in
Facebook 15 Microsoft 12 Apple 8
26.5K Views
Medium Frequency
~5 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen