Shortest Word Distance III
The problem is about finding the shortest distance between two words in a list of words. Here is the Python solution:
|
|
In this solution, we use two pointers: index1
and index2
to store the most recent locations of word1
and word2
.
We iterate through wordsDict
, and when we encounter word1
or word2
, we update the corresponding index.
In case word1
and word2
are the same, we need to handle this situation differently. We always update index2
to the last seen index before updating index1
again. This ensures we don’t calculate the distance between the word and itself.
We keep track of the min_distance
in the loop. After scanning all words, we return min_distance
, which represents the shortest distance between word1
and word2
.
The task is to find the shortest distance between two given words, word1
and word2
, in a list of words wordsDict
. The words may or may not be different. The solution will involve iterating through the list and tracking the last seen indices of the two words.
Here’s a step-by-step approach:
- Initialize two variables to store the last seen indices of
word1
andword2
. Set them to negative values initially, as they are not seen yet. - Initialize a variable to store the minimum distance and set it to a large number.
- Iterate through the list, and if the current word is equal to either
word1
orword2
, update the corresponding last seen index and calculate the distance. - If
word1
andword2
are the same, take care to handle the case where the current word is equal to bothword1
andword2
.
Here’s the code:
|
|
The code first checks if word1
is the same as word2
and handles that special case. Otherwise, it simply updates the last seen indices for word1
and word2
and calculates the minimum distance.
The time complexity of this function is O(n), where n is the number of words in wordsDict
. The space complexity is O(1), as we are only using a constant amount of extra space.