Problem Description
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)
Solutions
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;
}
}
Related LeetCode Problems
Loading editor...