Shortest Word Distance Problem
Description
LeetCode Problem 243.
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 * 10^41 <= wordsDict[i].length <= 10wordsDict[i]consists of lowercase English letters.word1andword2are inwordsDict.word1 != word2
Solution
Approach: Track the Last Positions
Walk the list once and remember i, the latest index of word1, and j, the latest index of word2 (both start at -1). Each time we see one of the two words, update its index, and if both have been seen, compare abs(i - j) with the best distance so far.
Why only the latest positions? The closest pair always has the two words next to each other in the sequence of their occurrences: if there were another word1 or word2 between them, that one would form a closer pair. When we reach an occurrence, the latest occurrence of the other word is the only one it can form such a pair with, so nothing is missed.
Complexity: O(n · L) time, where n is the number of words and L the word length (for the string comparisons). O(1) extra space.
class Solution:
def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
i = j = -1 # the latest index of word1 and of word2
ans = len(wordsDict)
for k, w in enumerate(wordsDict):
if w == word1:
i = k
elif w == word2:
j = k
if i != -1 and j != -1:
ans = min(ans, abs(i - j))
return ans