2025-08-20 14:47:52 +0000 UTC

Shortest Distance to Target String in a Circular Array

Code

class Solution:
    def closestTarget(self, words: List[str], target: str, startIndex: int) -> int:
        n = len(words)
        for i in range(n):
            left, right = (startIndex - i + n) % n, (startIndex + i) % n
            if words[left] == target or words[right] == target:
                return i
        return -1