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 #
- Loop (
i) overnums:- If
start + i < len(nums)andnums[start+i] == target:- Return
i.
- Return
- If
start - i >= 0andnums[start-i] == target:- Return
i.
- Return
- If
- Return
02.
Complexity #
Time complexity: .
Space complexity: .