2515. Shortest Distance to Target String in a Circular Array
</> Solution
/**
* Problem: LeetCode 2515 - Shortest Distance to Target String in a Circular Array
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int closestTarget(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 direct = Math.abs(i - startIndex);
int circular = n - direct;
minDistance = Math.min(minDistance, Math.min(direct, circular));
}
}
return minDistance == Integer.MAX_VALUE ? -1 : minDistance;
}
}
"""
Problem: LeetCode 2515 - Shortest Distance to Target String in a Circular Array
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def closestTarget(self, words: List[str], target: str, startIndex: int) -> int:
n = len(words)
min_dist = float('inf')
for i, word in enumerate(words):
if word == target:
direct = abs(i - startIndex)
circular = n - direct
min_dist = min(min_dist, direct, circular)
return -1 if min_dist == float('inf') else min_dist
/**
* Problem: LeetCode 2515 - Shortest Distance to Target String in a Circular Array
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
using namespace std;
class Solution {
public:
int closestTarget(vector<string>& words, string target, int startIndex) {
int n = words.size();
int minDistance = INT_MAX;
for (int i = 0; i < n; i++) {
if (words[i] == target) {
int direct = abs(i - startIndex);
int circular = n - direct;
minDistance = min(minDistance, min(direct, circular));
}
}
return minDistance == INT_MAX ? -1 : minDistance;
}
};
/**
* Problem: LeetCode 2515 - Shortest Distance to Target String in a Circular Array
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {string[]} words
* @param {string} target
* @param {number} startIndex
* @return {number}
*/
var closestTarget = function(words, target, startIndex) {
const n = words.length;
let minDistance = Infinity;
for (let i = 0; i < n; i++) {
if (words[i] === target) {
const direct = Math.abs(i - startIndex);
const circular = n - direct;
minDistance = Math.min(minDistance, Math.min(direct, circular));
}
}
return minDistance === Infinity ? -1 : minDistance;
};