243. Shortest Word Distance

small data

time: O(n)

space: O(1)

class Solution {
    public int shortestDistance(String[] wordsDict, String word1, String word2) {
        int a = -1;
        int b = -1;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < wordsDict.length; i++) {
            if (wordsDict[i].equals(word1)) {
                a = i; 
            } else if (wordsDict[i].equals(word2)) {
                b = i;
            }
            if (a != -1 && b != -1) {
               min = Math.min(min, Math.abs(a - b)); 
            }
        }
        return min;
    }
}

Last updated