Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Between two indices in a circular array, the two directional distances sum to the array length. If the direct absolute difference is d, the shortest route is min(d, n - d). Compare this for every target occurrence.
Approach
Scan the words and, whenever a word equals target, update the minimum with both its direct and wraparound distance from startIndex. Return the minimum, or -1 if no matching word was found. A match at the starting index yields zero, and repeated target words are all considered because the nearest one may lie across the array boundary.
class Solution:
def closestTarget(self, words: List[str], target: str, startIndex: int) -> int:
n = len(words)
res = inf
for i in range(n):
if words[i] == target:
d = abs(i - startIndex)
res = min(res, d, n - d)
return res if res != inf else -1Complexity analysis
Let n = words.length. Time: O(n) for the circular-distance scan. Auxiliary space: O(1).
