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.

2515. Shortest Distance to Target String in a Circular Array

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:

  1. Initialize minDistance to a large number and set found flag to false.
  2. Iterate through the circular array starting from startIndex.
  3. For each position, calculate the distance to the target string in both directions (next and previous).
  4. Update minDistance with the minimum of the previous minimum distance and the newly calculated distances.
  5. If the target string is found at any position, set found flag to true.
  6. Finally, return -1 if the target string was not found, else return the minDistance.

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.

Back to LeetCode Solutions