LeetCode-in-Java

2515. Shortest Distance to Target String in a Circular Array

Easy

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.

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

Example 2:

Input: words = [“a”,”b”,”leetcode”], target = “leetcode”, startIndex = 0

Output: 1

Explanation: We start from index 0 and can reach “leetcode” by

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:

Solution

public class Solution {
    public int closetTarget(String[] words, String target, int startIndex) {
        int n = words.length;
        if (words[startIndex].equals(target)) {
            return 0;
        }
        int ld = -1;
        int rd;
        int ans = Integer.MAX_VALUE;
        for (int i = (startIndex + 1) % n; i != startIndex; i = (i + 1) % n) {
            if (words[i].equals(target)) {
                ld = i > startIndex ? startIndex + (n - i) : startIndex - i;
                rd = i > startIndex ? i - startIndex : n - startIndex + i;
                ans = Math.min(ans, Math.min(ld, rd));
            }
        }
        if (ld == -1) {
            return -1;
        }
        return ans;
    }
}