LeetCode 2515: Shortest Distance to Target String in a Circular Array Solution
Master LeetCode problem 2515 (Shortest Distance to Target String in a Circular Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we can iterate through the circular array of words starting from the given startIndex. For each step in either direction (next or previous), we calculate the minimum distance to reach the target string. We keep track of the minimum distance seen so far and return it as the final answer.
Here are the steps:
- Initialize
minDistanceto a large number and setfoundflag to false. - Iterate through the circular array starting from
startIndex. - For each position, calculate the distance to the target string in both directions (next and previous).
- Update
minDistancewith the minimum of the previous minimum distance and the newly calculated distances. - If the target string is found at any position, set
foundflag to true. - Finally, return
-1if the target string was not found, else return theminDistance.
The time complexity of this solution is O(N) where N is the number of words in the array. The space complexity is O(1) as we are using constant extra space.
Solution Code
class Solution {
public int shortestDistance(String[] words, String target, int startIndex) {
int n = words.length;
int minDistance = Integer.MAX_VALUE;
boolean found = false;
for (int i = 0; i < n; i++) {
if (words[i].equals(target)) {
found = true;
int distance = Math.min(Math.abs(i - startIndex), n - Math.abs(i - startIndex));
minDistance = Math.min(minDistance, distance);
}
}
return found ? minDistance : -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2515 (Shortest Distance to Target String in a Circular Array)?
This page provides optimized solutions for LeetCode problem 2515 (Shortest Distance to Target String in a Circular Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2515 (Shortest Distance to Target String in a Circular Array)?
The time complexity for LeetCode 2515 (Shortest Distance to Target String in a Circular Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2515 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2515 in Java, C++, or Python.