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 Element INPUT nums array (0-indexed) 0 1 2 3 4 1 2 3 4 start=3 5 target=5 Input Values nums = [1,2,3,4,5] target = 5 start = 3 Find index where nums[i]==5 ALGORITHM STEPS Early Termination Optimization 1 Initialize minDist = infinity 2 Expand from start Check left and right 3 Check if match If nums[i]==target, update 4 Early terminate Return when found closest Search Process start=3: check i=3 nums[3]=4 != 5 dist=1: check i=4 nums[4]=5 == 5 FOUND! FINAL RESULT Distance from start to target 1 2 3 4 5 dist = 1 i=3 i=4 OUTPUT 1 abs(4 - 3) = 1 Target 5 found at index 4 OK - Minimum distance = 1 Key Insight: Early Termination: Instead of checking all indices, expand outward from 'start' position. Check indices at distance 0, 1, 2, ... The first match found is guaranteed to have minimum distance. Time complexity: O(d) where d is the minimum distance, best case O(1), worst case O(n). TutorialsPoint - Minimum Distance to the Target Element | Early Termination Optimization
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