Problem Description
Explanation
To solve this problem, we can iterate through the circular array of words starting from the given startIndex
. For each step in either direction (next or previous), we calculate the minimum distance to reach the target string. We keep track of the minimum distance seen so far and return it as the final answer.
Here are the steps:
- Initialize
minDistance
to a large number and setfound
flag to false. - Iterate through the circular array starting from
startIndex
. - For each position, calculate the distance to the target string in both directions (next and previous).
- Update
minDistance
with the minimum of the previous minimum distance and the newly calculated distances. - If the target string is found at any position, set
found
flag to true. - Finally, return
-1
if the target string was not found, else return theminDistance
.
The time complexity of this solution is O(N) where N is the number of words in the array. The space complexity is O(1) as we are using constant extra space.
Solutions
class Solution {
public int shortestDistance(String[] words, String target, int startIndex) {
int n = words.length;
int minDistance = Integer.MAX_VALUE;
boolean found = false;
for (int i = 0; i < n; i++) {
if (words[i].equals(target)) {
found = true;
int distance = Math.min(Math.abs(i - startIndex), n - Math.abs(i - startIndex));
minDistance = Math.min(minDistance, distance);
}
}
return found ? minDistance : -1;
}
}
Loading editor...