1. Brute Force

class Solution:
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        n = len(wordsDict)
        res = n
        for i in range(n):
            if wordsDict[i] == word1:
                for j in range(n):
                    if wordsDict[j] == word2:
                        res = min(res, abs(i - j))
        return res

Time & Space Complexity

  • Time complexity: O(n2⋅m)O(n ^ 2 \cdot m)
  • Space complexity: O(1)O(1)

Where nn is the number of words in wordsDictwordsDict and mm is the maximum length of a word.


2. Two Pointers

class Solution:
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        idx1, idx2 = [], []
        for i, word in enumerate(wordsDict):
            if word == word1:
                idx1.append(i)
            elif word == word2:
                idx2.append(i)

        res = len(wordsDict)
        i = j = 0
        while i < len(idx1) and j < len(idx2):
            res = min(res, abs(idx1[i] - idx2[j]))
            if idx1[i] < idx2[j]:
                i += 1
            else:
                j += 1
        return res

Time & Space Complexity

  • Time complexity: O(n⋅m)O(n \cdot m)
  • Space complexity: O(n)O(n)

Where nn is the number of words in wordsDictwordsDict and mm is the maximum length of a word.


3. Iteration - I

class Solution:
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        i1 = i2 = -1
        res = len(wordsDict)
        for i, word in enumerate(wordsDict):
            if word == word1:
                i1 = i
            elif word == word2:
                i2 = i

            if i1 != -1 and i2 != -1:
                res = min(res, abs(i1 - i2))
        return res

Time & Space Complexity

  • Time complexity: O(n⋅m)O(n \cdot m)
  • Space complexity: O(1)O(1)

Where nn is the number of words in wordsDictwordsDict and mm is the maximum length of a word.


4. Iteration - II

class Solution:
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        prev = -1
        res = len(wordsDict)
        for i, word in enumerate(wordsDict):
            if word == word1 or word == word2:
                if prev != -1 and wordsDict[prev] != word:
                    res = min(res, i - prev)
                prev = i
        return res

Time & Space Complexity

  • Time complexity: O(n⋅m)O(n \cdot m)
  • Space complexity: O(1)O(1)

Where nn is the number of words in wordsDictwordsDict and mm is the maximum length of a word.