Back to writing

243. Shortest Word Distance

243. Shortest Word Distance

Easy


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 1:

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

Example 2:

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

 

Constraints:

  • 2 <= wordsDict.length <= 3 * 104
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.
  • word1 != word2

 class Solution:
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:

        w1 = -1
        w2 = -1
        res = sys.maxsize

        for i, word in enumerate(wordsDict):

            if word == word1:
                w1=i
            elif word == word2:
                w2=i

            if w1 != -1 and w2 != -1:
                res = min(res, abs(w2-w1))
                if res == 1:
                    return res

        return res

Started keeping online notes!

Strategy