Skip to content

2515. Shortest Distance to Target String in a Circular Array

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] is words[(i + 1) % n] and the previous element of words[i] is words[(i - 1 + n) % n], where n is the length of words.

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 <= 100
  • 1 <= words[i].length <= 100
  • words[i] and target consist of only lowercase English letters.
  • 0 <= startIndex < words.length

Solutions

Solution 1: Single Traversal

We traverse the array \(\textit{words}\)\(,\) find the words equal to \(\textit{target}\), and compute their distance \(t\) from \(\textit{startIndex}\). The shortest distance in this case is \(\min(t, n - t)\), so we only need to keep updating the minimum value.

The time complexity is \(O(n)\), where \(n\) is the length of the array. The space complexity is \(O(1)\).

1
2
3
4
5
6
7
8
9
class Solution:
    def closestTarget(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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public int closestTarget(String[] words, String target, int startIndex) {
        int n = words.length;
        int ans = n;
        for (int i = 0; i < n; i++) {
            if (words[i].equals(target)) {
                int t = Math.abs(i - startIndex);
                ans = Math.min(ans, Math.min(t, n - t));
            }
        }
        return ans == n ? -1 : ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    int closestTarget(vector<string>& words, string target, int startIndex) {
        int n = words.size();
        int ans = n;
        for (int i = 0; i < n; i++) {
            if (words[i] == target) {
                int t = abs(i - startIndex);
                ans = min({ans, t, n - t});
            }
        }
        return ans == n ? -1 : ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func closestTarget(words []string, target string, startIndex int) int {
    n := len(words)
    ans := n
    for i, w := range words {
        if w == target {
            t := i - startIndex
            if t < 0 {
                t = -t
            }
            ans = min(ans, t, n-t)
        }
    }
    if ans == n {
        return -1
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function closestTarget(words: string[], target: string, startIndex: number): number {
    const n = words.length;
    let ans = n;
    for (let i = 0; i < n; i++) {
        if (words[i] === target) {
            const t = Math.abs(i - startIndex);
            ans = Math.min(ans, t, n - t);
        }
    }
    return ans === n ? -1 : ans;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
impl Solution {
    pub fn closest_target(words: Vec<String>, target: String, start_index: i32) -> i32 {
        let n = words.len() as i32;
        let mut ans = n;
        for (i, w) in words.iter().enumerate() {
            if w == &target {
                let t = (i as i32 - start_index).abs();
                ans = ans.min(t.min(n - t));
            }
        }
        if ans == n { -1 } else { ans }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#define min(a, b) ((a) < (b) ? (a) : (b))

int closestTarget(char** words, int wordsSize, char* target, int startIndex) {
    int n = wordsSize;
    int ans = n;

    for (int i = 0; i < n; i++) {
        if (strcmp(words[i], target) == 0) {
            int t = abs(i - startIndex);
            int dist = min(t, n - t);
            ans = min(ans, dist);
        }
    }

    return ans == n ? -1 : ans;
}

Comments