Problem Description
Given an array of strings wordsDict and two different strings word1 and word2 that already exist in the array, return the shortest distance between these two words in the list.
Key Insights
- Perform a single pass through wordsDict.
- Use two variables to track the most recent indices of word1 and word2.
- Calculate the absolute difference between indices every time both words have been encountered.
- Update the shortest distance seen result during the iteration.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in wordsDict. Space Complexity: O(1), since only a constant number of variables are used.
Solution
We use a one-pass approach that iterates over the list while maintaining two pointers (or indices) for word1 and word2. When either word is encountered, update its corresponding pointer. When both pointers have valid indices, compute the current distance and update the minimum distance if needed. This simple but efficient method leverages constant extra space and ensures linear time processing.
Code Solutions
Below are code solutions with line-by-line comments.