Skip to main content
Back to problems
#2515
Easy Algorithms

Shortest distance to target string in a circular array

Array String
50.6% acceptance
Feb 25, 2026
375
24
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn closest_target(words: Vec<String>, target: String, start_index: i32) -> i32 {
    let n = words.len() as i32;
    let mut ans = -1i32;
    for (i, w) in words.iter().enumerate() {
      if w == &target {
        let i = i as i32;
        let diff = (i - start_index).abs();
        let dist = diff.min(n - diff);
        if ans == -1 || dist < ans {
          ans = dist;
        }
      }
    }
    ans
  }
}