Description
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.
- Formally, the next element of
words[i]iswords[(i + 1) % n]and the previous element ofwords[i]iswords[(i - 1 + n) % n], wherenis the length ofwords.
Starting from startIndex, you can move to either the next word or the previous word with 1 step at a time.
Return the shortest distance needed to reach the string target. If the string target does not exist in words, return -1.
Example 1:
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.
Example 2:
Input: words = ["a","b","leetcode"], target = "leetcode", startIndex = 0 Output: 1 Explanation: We start from index 0 and can reach "leetcode" by - moving 2 units to the right to reach index 2. - moving 1 unit to the left to reach index 2. The shortest distance to reach "leetcode" is 1.
Example 3:
Input: words = ["i","eat","leetcode"], target = "ate", startIndex = 0
Output: -1
Explanation: Since "ate" does not exist in words, we return -1.
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]andtargetconsist of only lowercase English letters.0 <= startIndex < words.length
Solutions
This function searches for a target word in a circular array starting from a given position and returns the minimum distance to that word. It uses the modulo operator (%) to wrap around the array boundaries, checking in both directions simultaneously—moving left with (start - i + n) % n and right with (start + i) % n—where i increases from 0 to half the array length. On each iteration, if either direction finds a match, the function immediately returns i (the distance traveled), making this an efficient bidirectional search that avoids checking the entire array. If no match is found after checking half the array in both directions, it returns -1.
/**
* @param {string[]} words
* @param {string} target
* @param {number} start
* @return {number}
*/
var closestTarget = function(words, target, start) {
const n = words.length;
const len = Math.ceil(n / 2);
for (let i = 0; i <= len; i++) {
if (words[(start - i + n) % n] === target || words[(start + i) % n] === target) {
return i;
}
}
return -1;
};