LeetCode 243: Shortest Word Distance

ArrayString

LeetCode 243 Solution Explanation

Explanation

The problem asks us to find the shortest distance between two words in a given list of words. We need to find the minimum distance between the two words.

To solve this problem, we can iterate through the list of words and keep track of the indices of the two words we are looking for. As we iterate, we update the minimum distance whenever we find a pair of indices for the two words.

  • Time complexity: O(n), where n is the number of words in the list.
  • Space complexity: O(1)

LeetCode 243 Solutions in Java, C++, Python

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int index1 = -1;
        int index2 = -1;
        int minDistance = Integer.MAX_VALUE;

        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                index1 = i;
            } else if (words[i].equals(word2)) {
                index2 = i;
            }

            if (index1 != -1 && index2 != -1) {
                minDistance = Math.min(minDistance, Math.abs(index1 - index2));
            }
        }

        return minDistance;
    }
}

Interactive Code Editor for LeetCode 243

Improve Your LeetCode 243 Solution

Use the editor below to refine the provided solution for LeetCode 243. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems