Problem Description
Given an array of strings wordsDict and two strings word1 and word2 that already exist in the array, return the shortest distance (in indices) between occurrences of these two words. Note that word1 and word2 may be the same, so the solution needs to handle this special case separately.
Key Insights
- When word1 and word2 are different, maintain two indices: one for the latest occurrence of word1 and one for word2.
- When word1 and word2 are the same, compute the distance between consecutive occurrences.
- Perform a single pass through wordsDict to achieve optimal time complexity.
Space and Time Complexity
Time Complexity: O(n), where n is the length of wordsDict. Space Complexity: O(1) since only constant extra space is used.
Solution
The solution uses a single pass algorithm. For different words, we update the latest positions of word1 and word2 as we traverse the array and calculate the minimum distance whenever both words have been seen. When word1 and word2 are the same, we simply track the last seen index and update the minimum distance when the current index and last seen index pose a smaller gap. This conditional handling ensures the solution works correctly for both scenarios.