Shortest Word Distance III
This challenge asks you to find the shortest distance between two specific words in a given list of words. Understanding and efficiently calculating distances between elements in a sequence is a common task in text processing, data analysis, and search algorithms. Your solution should be optimized for performance, especially with large input lists.
Problem Description
You are given a list of words (words) and two target words, word1 and word2. Your task is to find the minimum distance between the indices of word1 and word2 in the words list. The distance is calculated as the absolute difference between their indices.
Requirements:
- The input list
wordscan contain duplicate words. word1andword2may or may not be present in thewordslist.- If either
word1orword2is not found in the list, return -1. - If both
word1andword2are found, return the minimum distance between their indices.
Expected Behavior:
The function should iterate through the words list, keeping track of the most recent indices of word1 and word2. For each word in the list, it should calculate the distance between the current word and the most recent occurrences of word1 and word2, updating the minimum distance found so far.
Edge Cases to Consider:
- Empty
wordslist. word1orword2not present inwords.word1andword2are the same word.- Large input list
wordsto test performance.
Examples
Example 1:
Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "practice", word2 = "coding"
Output: 3
Explanation: The index of "practice" is 0 and the index of "coding" is 3. The distance between them is |0 - 3| = 3.
Example 2:
Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "makes"
Output: 1
Explanation: The index of "coding" is 3 and the index of the first "makes" is 1. The distance between them is |3 - 1| = 2. The index of the second "makes" is 4. The distance between "coding" and the second "makes" is |3 - 4| = 1. The minimum distance is 1.
Example 3:
Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "hello", word2 = "coding"
Output: -1
Explanation: "hello" is not present in the list, so the function should return -1.
Constraints
1 <= words.length <= 10^5words[i].length <= 10word1.length <= 10word2.length <= 10- The characters in
words,word1, andword2are ASCII lowercase letters. - The time complexity should be O(n), where n is the length of the
wordslist.
Notes
Consider using two pointers or a dictionary/hash map to store the indices of word1 and word2 as you iterate through the list. This will allow you to efficiently calculate the distance between the words without repeatedly searching the list. Think about how to handle the case where a word appears multiple times. The most recent index is what matters for calculating the distance.