Shortest Word Distance III Problem
#245
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 245.
Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list.
Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.
Example 1:
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1
Example 2:
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
Output: 3
Constraints:
1 <= wordsDict.length <= 10^51 <= wordsDict[i].length <= 10wordsDict[i]consists of lowercase English letters.word1andword2are inwordsDict.
Solution
Approach: Two Cases
This is Shortest Word Distance with one twist: word1 and word2 may be the same word. The problem promises that they are then two different occurrences in the list.
- Different words: the same scan as before. Track
i, the latest index ofword1, andj, the latest index ofword2, and after each step compareabs(i - j)with the best distance. - Same word: using the two-index scan here would set
iandjto the same position and report0. Instead keep a single indexlastof the previous occurrence. Each time we see the word again, the distance to the previous occurrencek - lastis a candidate, then setlast = k. The closest two occurrences are always neighbors in this sequence, so comparing with the previous one is enough.
The else if in the different-words case keeps one index from being counted as both words.
Complexity: O(n · L) time, where n is the number of words and L the word length. O(1) extra space.
class Solution:
def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
ans = len(wordsDict)
if word1 == word2:
# Same word: the answer is the closest pair of consecutive occurrences.
last = -1
for k, w in enumerate(wordsDict):
if w == word1:
if last != -1:
ans = min(ans, k - last)
last = k
else:
i = j = -1 # the latest index of word1 and of word2
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