Intuition
Walk the array once. At every index i whose word equals target, compute the circular distance from startIndex — the smaller of going forward |i - startIndex| or going backward n - |i - startIndex|. Track the minimum.
Explanation
Why circular distance is min(|i - s|, n - |i - s|)
On a circle of n positions, you can travel from s to i two ways: clockwise ((i - s) mod n steps) or counter-clockwise ((s - i) mod n steps). They sum to n, so the shorter is min(d, n - d) where d = |i - s|.
Steps
- Initialise
best = -1(sentinel for "no occurrence found yet"). - Walk
ifrom0ton - 1:- If
words[i] != target, skip. - Otherwise compute
d = abs(i - startIndex), thend = min(d, n - d). - If
best == -1ord < best, setbest = d.
- If
- Return
best.
Walk-through
words = ["hello", "i", "am", "coding", "hello"], target = "hello", startIndex = 1. n = 5.
| i | words[i] | d = abs(i - 1) | min(d, 5 - d) | best |
|---|---|---|---|---|
| 0 | hello | 1 | min(1, 4) = 1 | 1 |
| 1 | i | (skip) | 1 | |
| 2 | am | (skip) | 1 | |
| 3 | coding | (skip) | 1 | |
| 4 | hello | 3 | min(3, 2) = 2 | 1 |
Return 1. ✓
Another, target = "coding", startIndex = 0:
- Only
i = 3matches.d = 3,min(3, 2) = 2. Return2.
Target not in words: loop never updates best; return -1.
Edge cases
- Target appears at
startIndexitself:d = 0,min(0, n) = 0— return0immediately on that iteration. - Single occurrence: the answer is just that one circular distance.
- No occurrence: return
-1via the sentinel.
Complexity
- Time:
O(n)— single pass. - Space:
O(1).
Implementation
import java.util.*;
class Solution {
public int closetTarget(String[] words, String target, int startIndex) {
int n = words.length;
int best = -1;
for (int i = 0; i < n; i++) {
if (!words[i].equals(target)) continue;
int d = Math.min(Math.abs(i - startIndex), n - Math.abs(i - startIndex));
if (best == -1 || d < best) best = d;
}
return best;
}
}