# 243. Shortest Word Distance

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MaqKqvdq7loJ7-u1FEu%2F-Mar0rI1CrtoFtlb5xMq%2Fimage.png?alt=media\&token=47de5422-3b57-469f-b247-8c4a5cd10693)

small data&#x20;





time: O(n)

space: O(1)

```java
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;
    }
}
```
