Leetcode #2515: Shortest Distance to Target String in a Circular Array
In this guide, we solve Leetcode #2515 Shortest Distance to Target String in a Circular Array in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed circular string array words and a string target. A circular array means that the array's end connects to the array's beginning.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, String
Intuition
We need to scan characters while tracking positions or counts.
A simple state machine keeps the logic precise.
Approach
Iterate through the string once and update the state for each character.
Use a map or array if you need fast lookups.
Steps:
- Iterate through characters.
- Maintain necessary state.
- Build or validate the output.
Example
Input: words = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1
Output: 1
Explanation: We start from index 1 and can reach "hello" by
- moving 3 units to the right to reach index 4.
- moving 2 units to the left to reach index 4.
- moving 4 units to the right to reach index 0.
- moving 1 unit to the left to reach index 0.
The shortest distance to reach "hello" is 1.
Python Solution
class Solution:
def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:
n = len(words)
ans = n
for i, w in enumerate(words):
if w == target:
t = abs(i - startIndex)
ans = min(ans, t, n - t)
return -1 if ans == n else ans
Complexity
The time complexity is O(n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.