MediumNo. 0245LeetCode Premium

Shortest Word Distance III — LeetCode 245 Python Solution

Pattern
Hash Map
Topics
Array, String
Reading time
4 min

The problem

Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list. Note that word1 and word2 may be the same.

Example

Input
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output
1

Python solution

PythonSolution
class Solution:
    def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        ans = len(wordsDict)
        if word1 == word2:
            j = -1
            for i, w in enumerate(wordsDict):
                if w == word1:
                    if j != -1:
                        ans = min(ans, i - j)
                    j = i
        else:
            i = j = -1
            for k, w in enumerate(wordsDict):
                if w == word1:
                    i = k
                if w == word2:
                    j = k
                if i != -1 and j != -1:
                    ans = min(ans, abs(i - j))
        return ans

Complexity

Time
O(n)where n is the length of the array wordsDict
Space · auxiliary
O(1)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 245. Shortest Word Distance III is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 245. Shortest Word Distance III?

LeetCode 245. Shortest Word Distance III is rated Medium on LeetCode.

What is the time complexity of LeetCode 245. Shortest Word Distance III?

The Python solution on this page runs in O(n), where n is the length of the array \textit{wordsDict}.

What is the space complexity of LeetCode 245. Shortest Word Distance III?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 245. Shortest Word Distance III cover?

LeetCode 245. Shortest Word Distance III is tagged Array and String on LeetCode.

Is LeetCode 245. Shortest Word Distance III a premium problem?

Yes. LeetCode 245. Shortest Word Distance III 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.

Free to download. Check it runs on your machine, then pick a plan.