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.
wordsDict[i] consists of lowercase English letters.
word1 and word2 are in wordsDict.
Solutions
Solution 1: Case Analysis
Thinking
\(word1\) may equal \(word2\), in which case the answer is the gap between consecutive occurrences of that word; otherwise it is the usual two-word gap.
Track the last index accordingly: one pointer when the words coincide, two pointers when they differ.
First, we check whether \(\textit{word1}\) and \(\textit{word2}\) are equal:
If they are equal, iterate through the array \(\textit{wordsDict}\) to find two indices \(i\) and \(j\) of \(\textit{word1}\), and compute the minimum value of \(i-j\).
If they are not equal, iterate through the array \(\textit{wordsDict}\) to find the indices \(i\) of \(\textit{word1}\) and \(j\) of \(\textit{word2}\), and compute the minimum value of \(i-j\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{wordsDict}\). The space complexity is \(O(1)\).