Leetcode 2515. Shortest Distance to Target String in a Circular Array
You are given an array of strings words
, a target string target
, and an integer startIndex
. The array is considered to be circular, meaning that the next element of the last element is the first element of the array.
You need to find the shortest distance from startIndex
to any occurrence of target
. The distance between any two indices i
and j
is the minimum between the number of steps to go from i
to j
clockwise and the number of steps to go from i
to j
counterclockwise.
Return the shortest distance as an integer.
words
and identify all indices where words[i]
equals the target
.startIndex
:
startIndex
.Here’s how we can implement this in Java:
public class Solution {
public int closetTarget(String[] words, String target, int startIndex) {
int n = words.length;
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (words[i].equals(target)) {
int clockwiseDistance = (i - startIndex + n) % n;
int counterClockwiseDistance = (startIndex - i + n) % n;
int currentMinDistance = Math.min(clockwiseDistance, counterClockwiseDistance);
minDistance = Math.min(minDistance, currentMinDistance);
}
}
return minDistance;
}
public static void main(String[] args) {
Solution solution = new Solution();
String[] words = {"hello", "world", "leetcode", "hello"};
String target = "hello";
int startIndex = 1;
System.out.println(solution.closetTarget(words, target, startIndex)); // Output: 1
}
}
The time complexity of the above solution is (O(n)), where (n) is the number of elements in the array words
:
target
.This ensures we get the shortest distance efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?