Minimum Distance to the Target Element - Problem

Imagine you're standing at a specific position on a number line and need to find the closest occurrence of your target number. Given an integer array nums and two integers target and start, your goal is to find the minimum distance from the starting position to any occurrence of the target element.

More formally, you need to:

  • Find an index i where nums[i] == target
  • Calculate the absolute distance abs(i - start)
  • Return the minimum possible distance among all valid indices

Example: If nums = [1,2,3,4,5], target = 3, and start = 1, the target 3 is at index 2, so the distance is abs(2-1) = 1.

Note: It's guaranteed that the target exists in the array.

Input & Output

example_1.py โ€” Basic Example
$ Input: nums = [1,2,3,4,5], target = 3, start = 1
โ€บ Output: 1
๐Ÿ’ก Note: The target 3 is at index 2. Distance from start position 1 is |2-1| = 1.
example_2.py โ€” Multiple Occurrences
$ Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
โ€บ Output: 0
๐Ÿ’ก Note: Target 1 exists at every index including start position 0, so minimum distance is |0-0| = 0.
example_3.py โ€” Edge Position
$ Input: nums = [1,2,3,4,5], target = 1, start = 4
โ€บ Output: 4
๐Ÿ’ก Note: Target 1 is at index 0. Distance from start position 4 is |0-4| = 4.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 104
  • 0 โ‰ค start < nums.length
  • target is guaranteed to exist in nums

Visualization

Tap to expand
Street (Array)1Index 02START (1)๐Ÿ“ You are here3Index 2โ˜• Target!4Index 35Index 4Distance = 1Minimum Distance Found: 1|2 - 1| = 1
Understanding the Visualization
1
Start Position
You're standing at position 'start' on the street (array)
2
Scan Street
Walk through the street checking each building (array element)
3
Find Coffee Shops
When you find a coffee shop (target element), measure distance from start
4
Track Closest
Keep track of the shortest distance found so far
5
Final Answer
Return the minimum distance to any coffee shop
Key Takeaway
๐ŸŽฏ Key Insight: We only need one pass through the array since we're looking for the minimum distance - no complex data structures needed, just track the smallest distance as we scan!
Asked in
Amazon 35 Google 28 Meta 22 Microsoft 18
23.5K Views
Medium Frequency
~8 min Avg. Time
892 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