Problem statement

https://binarysearch.com/problems/Minimum-Distance-of-Two-Words-in-a-Sentence/

Solution

Equal to Leetcode 0243 Shortest Word Distance.

Complexity

It is O(n) for time and O(1) for space.

Code

class Solution:
    def solve(self, text, word1, word2):
        p1, p2 = -float("inf"), float("inf")
        s = text.split()
        if word1 not in s or word2 not in s: return -1
        ans = p2 - p1
        for i, word in enumerate(s):
            if word == word1:
                p1 = i
                ans = min(ans, abs(p2 - p1))
            if word == word2:
                p2 = i
                ans = min(ans, abs(p2 - p1))
                
        return ans - 1