> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Shortest Word Distance II Python Solution

> Tested Python solution for LeetCode 244 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 244, [Medium](/catalog/medium). Topics: [Design](/catalog/topics/design), [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Two Pointers](/catalog/topics/two-pointers), [String](/catalog/topics/string). [View on LeetCode](https://leetcode.com/problems/shortest-word-distance-ii/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 244   # by problem number
lcpy gen -s shortest_word_distance_ii   # by problem name
```

## Problem

Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.

Implement the `WordDistance` class:

* `WordDistance(String[] wordsDict)` initializes the object with the strings array `wordsDict`.
* `int shortest(String word1, String word2)` returns the shortest distance between `word1` and `word2` in the array `wordsDict`.

### Examples

```
Input
["WordDistance", "shortest", "shortest"]
[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
Output
[null, 3, 1]

Explanation
WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
wordDistance.shortest("coding", "practice"); // return 3
wordDistance.shortest("makes", "coding");  // return 1
```

### Constraints

* `1 <= wordsDict.length <= 3 * 10^4`
* `1 <= wordsDict[i].length <= 10`
* `wordsDict[i]` consists of lowercase English letters.
* `word1` and `word2` are in `wordsDict`.
* `word1 != word2`
* At most `5000` calls will be made to `shortest`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_word_distance_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_word_distance_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import defaultdict


class WordDistance:
    # Time: O(n) for __init__, O(k + m) per shortest call
    # Space: O(n)
    def __init__(self, words_dict: list[str]) -> None:
        self.indices: defaultdict[str, list[int]] = defaultdict(list)
        for i, word in enumerate(words_dict):
            self.indices[word].append(i)

    def shortest(self, word1: str, word2: str) -> int:
        positions1 = self.indices[word1]
        positions2 = self.indices[word2]
        shortest = 10**9
        i = 0
        j = 0
        while i < len(positions1) and j < len(positions2):
            shortest = min(shortest, abs(positions1[i] - positions2[j]))
            if positions1[i] <= positions2[j]:
                i += 1
            else:
                j += 1
        return shortest
```

## Complexity

| Time | Space |
| - | - |
| O(n) for **init**, O(k + m) per shortest call | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.