Minimum Distance to the Target Element

Intuition #

The problem is asking to return abs(i - start) if nums[i] == target. The brute force solution is to check each number starting from 0 until len(nums).

What if we started from start1 and went to the right and to the left. We can then check from the right first since i will be greater than start, then from the left where i will be less that start.

If we find target we directly return i, because we already have the minimum abs(i - start).

Approach #

Complexity #

Code #

 1func getMinDistance(nums []int, target int, start int) int {
 2	for i := range nums {
 3		if start+i < len(nums) && nums[start+i] == target {
 4			return i
 5		}
 6
 7		if start-i >= 0 && nums[start-i] == target {
 8			return i
 9		}
10	}
11
12	return 0
13}

  1. We can start from start since start is in the bounds of 0 and len(nums)-1↩︎

  2. When we hit this return it means the target number is not in the array, but the target is guaranteed to be present in the description. ↩︎