Shortest Word Distance III – Python 3 (Week 13 – 05)

class Solution:
    def shortestWordDistance(self, words: List[str], word1: str, word2: str) -> int:
        
    
        w1, w2 = float('inf'), float('inf')
        ans = float('inf')
        same = word1 == word2
        for i in range(len(words)):
            if words[i] == word1:
                w1 = i
                ans = min(ans, abs(w1 - w2))
                if same:
                    w2 = w1
            elif words[i] == word2:
                w2 = i
                ans = min(ans, abs(w1 - w2))
                

        return ans

Time O(n). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started