Shortest Word Distance II — LeetCode 244 Python Solution

MediumLeetCode PremiumDesignArrayHash TableTwo PointersString
Problem
#244
Reading time
4 min

The 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.

Example

Input
["WordDistance", "shortest", "shortest"]
Output
[null, 3, 1]
Explanation
WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);

Python solution

Python
class WordDistance:
    def __init__(self, wordsDict: List[str]):
        self.d = defaultdict(list)
        for i, w in enumerate(wordsDict):
            self.d[w].append(i)

    def shortest(self, word1: str, word2: str) -> int:
        a, b = self.d[word1], self.d[word2]
        ans = inf
        i = j = 0
        while i < len(a) and j < len(b):
            ans = min(ans, abs(a[i] - b[j]))
            if a[i] <= b[j]:
                i += 1
            else:
                j += 1
        return ans


# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 244. Shortest Word Distance II is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 244. Shortest Word Distance II?
LeetCode 244. Shortest Word Distance II is rated Medium on LeetCode.
What is the time complexity of LeetCode 244. Shortest Word Distance II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 244. Shortest Word Distance II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 244. Shortest Word Distance II cover?
LeetCode 244. Shortest Word Distance II is tagged Design, Array, Hash Table, Two Pointers and String on LeetCode.
Is LeetCode 244. Shortest Word Distance II a premium problem?
Yes. LeetCode 244. Shortest Word Distance II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview