Skip to content

2515. Shortest Distance to Target String in a Circular Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int closetTarget(vector<string>& words, string target, int startIndex) {
    const int n = words.size();

    for (int i = 0; i < n; ++i) {
      if (words[(startIndex + i + n) % n] == target)
        return i;
      if (words[(startIndex - i + n) % n] == target)
        return i;
    }

    return -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int closetTarget(String[] words, String target, int startIndex) {
    final int n = words.length;

    for (int i = 0; i < n; ++i) {
      if (words[(startIndex + i + n) % n].equals(target))
        return i;
      if (words[(startIndex - i + n) % n].equals(target))
        return i;
    }

    return -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def closetTarget(self, words: list[str], target: str, startIndex: int) -> int:
    n = len(words)

    for i in range(n):
      if words[(startIndex + i + n) % n] == target:
        return i
      if words[(startIndex - i + n) % n] == target:
        return i

    return -1