Shortest Word Distance — LeetCode 243 Python Solution

EasyLeetCode PremiumArrayString
Problem
#243
Pattern
Hash Map
Reading time
2 min

The problem

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

Example

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

Python solution

Python
class Solution:
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        i = j = -1
        ans = inf
        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

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 243. Shortest Word Distance 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 243. Shortest Word Distance?
LeetCode 243. Shortest Word Distance is rated Easy on LeetCode.
What topics does LeetCode 243. Shortest Word Distance cover?
LeetCode 243. Shortest Word Distance is tagged Array and String on LeetCode.
Is LeetCode 243. Shortest Word Distance a premium problem?
Yes. LeetCode 243. Shortest Word Distance 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