Shortest Word Distance
Input: word1 = “coding”, word2 = “practice”
Output: 3Input: word1 = "makes", word2 = "coding"
Output: 1Solution
One pass - O(n) time, O(1) space
class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int i1 = -1;
int i2 = -1;
int shortest = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
i1 = i;
}
if (words[i].equals(word2)) {
i2 = i;
}
if (i1 != -1 && i2 != -1) {
shortest = Math.min(Math.abs(i1 - i2), shortest);
}
}
return shortest;
}
}Reference
Last updated