Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

A target occurrence can lie on either side of start, and its distance is the absolute difference of indices. Since every occurrence is an independent candidate, a single full scan can keep the nearest one.

Approach

Initialize the best distance to infinity. For every index whose value equals target, minimize the answer with abs(index - start). Return the final minimum. The input guarantees at least one target occurrence, so the result is finite. If the starting position already contains the target, the best distance is zero, the smallest possible answer.

class Solution: def getMinDistance(self, nums: List[int], target: int, start: int) -> int: n = len(nums) res = inf for i in range(n): if nums[i] == target: res = min(res, abs(i - start)) return res

Complexity analysis

Let n = nums.length. Time: O(n) for the full scan. Auxiliary space: O(1).