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
iwherenums[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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code