LeetCode 245: Shortest Word Distance III Solution

Master LeetCode problem 245 (Shortest Word Distance III), a medium 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.

245. Shortest Word Distance III

Problem Explanation

Explanation

To solve this problem, we can iterate through the input array of words and keep track of the indices of the two target words. We update the indices as we encounter the target words. We then calculate the minimum distance between the two indices. If the words can be the same, we need to handle the case where the two indices are the same.

Algorithm:

  1. Initialize variables index1, index2, and minDistance to track the indices and minimum distance.
  2. Iterate through the input words array:
    • If the current word is equal to word1, update index1.
    • If the current word is equal to word2, update index2.
    • If both indices are valid, calculate the distance and update minDistance.
    • If word1 and word2 are the same, handle the case where index1 and index2 are the same.
  3. Finally, return minDistance.

Time Complexity: O(n) where n is the number of words in the input array.

Space Complexity: O(1)

Solution Code

class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int index1 = -1, index2 = -1;
        int minDistance = Integer.MAX_VALUE;
        
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                index1 = i;
            }
            if (words[i].equals(word2)) {
                if (word1.equals(word2)) {
                    index1 = index2;
                }
                index2 = i;
            }
            if (index1 != -1 && index2 != -1) {
                minDistance = Math.min(minDistance, Math.abs(index1 - index2));
            }
        }
        
        return minDistance;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 245 (Shortest Word Distance III)?

This page provides optimized solutions for LeetCode problem 245 (Shortest Word Distance III) 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 245 (Shortest Word Distance III)?

The time complexity for LeetCode 245 (Shortest Word Distance III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 245 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 245 in Java, C++, or Python.

Back to LeetCode Solutions