Leetcode 2515. Shortest Distance to Target String in a Circular Array
You are given an array of strings words
and a string target
. You need to determine the shortest distance between two identical occurrences of the target
string in a circular array.
A circular array means that after the last element, the array resumes from the first element again, forming a loop. If the target string appears only once or not at all, return -1
.
words
array be?words
array?target
is not present in the array?target
occurs exactly once?target
string appears.-1
.#include <vector>
#include <string>
#include <algorithm>
#include <climits> // For INT_MAX
int shortestDistanceToTargetString(const std::vector<std::string>& words, const std::string& target) {
std::vector<int> targetIndices;
// Collect indices of the target string's occurrences
for (int i = 0; i < words.size(); ++i) {
if (words[i] == target) {
targetIndices.push_back(i);
}
}
// If target appears less than 2 times, return -1
if (targetIndices.size() < 2) {
return -1;
}
int minDistance = INT_MAX;
int n = words.size();
// Compute the minimum distance between consecutive indices
for (size_t i = 1; i < targetIndices.size(); ++i) {
int distance = (targetIndices[i] - targetIndices[i-1] + n) % n;
minDistance = std::min(minDistance, distance);
}
// Wrap around: Consider distance from last occurrence back to the first occurrence
int wrapAroundDistance = (targetIndices[0] + n - targetIndices.back()) % n;
minDistance = std::min(minDistance, wrapAroundDistance);
return minDistance;
}
words
array once — O(n).target
— let’s denote this number as k
. Thus O(k), but since k
<= n
, this part is effectively O(n) in the worst case.k
is the number of occurrences. In the worst case, k
can be n
, making space complexity O(n).This algorithm provides an efficient solution to determine the shortest distance in a circular arrangement for given scenarios.
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?