[LeetCode] Shortest Distance to Target String in a Circular Array

2515. Shortest Distance to Target String in a Circular Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int closetTarget(vector<string>& words, string target, int startIndex) {
bool has = false;
for(auto w : words) {
if(w == target) has = true;
}
if(!has) return -1;
int res = 0;
int l = startIndex, r = startIndex;
while(words[l] != target and words[r] != target) {
res += 1;
l = (l - 1 + words.size()) % words.size();
r = (r + 1) % words.size();
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/25/PS/LeetCode/shortest-distance-to-target-string-in-a-circular-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.