Shortest Word Distance

Problem Summary

Key Observations

Main Concepts Used

Time & Space Complexity

Code

class Solution:
    def shortestDistance(self, words, word1, word2):
        indexWord1 = None
        indexWord2 = None
        minDistance = float("inf")

        for i, word in enumerate(words):
            if word == word1:
                indexWord1 = i
            elif word == word2:
                indexWord2 = i

            if indexWord1 != None and indexWord2 != None:
                minDistance = min(abs(indexWord1 - indexWord2), minDistance)
        return minDistance

Common Mistakes / Things I Got Stuck On