> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/hashtable/243.-shortest-word-distance.md).

# 243. Shortest Word Distance

![](/files/-Mar0rI1CrtoFtlb5xMq)

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