
Problem Statement
The task requires finding the shortest distance between two specified words in a given list of words, wordsDict. The words for comparison, word1 and word2, are guaranteed to be present in the list. The "shortest distance" refers to the minimum number of indices that separate the two words in the array. It is important to consider that word1 and word2 might refer to the same word, adding a layer of complexity since one has to find the minimum distance between two occurrences of the same word if they are identical. The problem focuses on efficiently identifying and calculating this minimum distance while navigating through the nuances of potential word repetition and different words.
Examples
Example 1
Input:
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output:
1
Example 2
Input:
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
Output:
3
Constraints
1 <= wordsDict.length <= 1051 <= wordsDict[i].length <= 10wordsDict[i]consists of lowercase English letters.word1andword2are inwordsDict.
Approach and Intuition
This task can be tackled efficiently by iterating through the list wordsDict and using a few variables to keep track of the positions of the words and the shortest distance found.
- Initialize two variables,
index1andindex2, to record the last seen indices ofword1andword2respectively. Both are initialized to some dummy values indicating they haven't been encountered yet. - Create a variable
min_distanceinitialized to a large number that will store the shortest distance found during the iteration. - As you iterate through
wordsDict, check for the occurrences ofword1andword2. - If
word1is encountered, updateindex1. Ifword2is also encountered (either as a separate word or the same asword1), updateindex2. - After updating indices, if both
index1andindex2are valid (i.e., they have been updated at least once from their initial dummy values), compute the distance between the two indices. - If the computed distance is smaller than
min_distance, updatemin_distance. - Continue this process until the end of the list. The value in
min_distanceat the end of the iteration will be the shortest distance betweenword1andword2.
This method efficiently computes the shortest distance with just one pass through the list, making it optimal considering the constraints provided.
Solutions
- C++
class Solution {
public:
int findMinDistance(vector<string>& dictionary, string w1, string w2) {
int minDist = INT_MAX;
int lastIndex = -1;
for (int idx = 0; idx < dictionary.size(); idx++) {
if (dictionary[idx] == w1 || dictionary[idx] == w2) {
if (lastIndex != -1 && (dictionary[lastIndex] != dictionary[idx] || w1 == w2)) {
minDist = min(minDist, idx - lastIndex);
}
lastIndex = idx;
}
}
return minDist;
}
};
This C++ solution aims to address the problem of finding the shortest distance between two words in an array, which may be the same word (hence considering occurrences of a single word). The implementation is straightforward, focusing on minimizing iterations and effectively utilizing storage to track indices.
- The function
findMinDistancereceives avector<string> dictionarycontaining the words, and twostringvariables,w1andw2, representing the words for which the distance needs to be calculated. - An integer
minDistis initialized toINT_MAXto keep track of the minimum distance found during the iteration. - Another integer
lastIndexis initialized to-1and serves as a marker to store the index of the previous occurrence of eitherw1orw2. - The function then iterates over the dictionary with a for loop. For each word at the current index (
idx):- If the current word matches
w1orw2, the algorithm checks if a previous index (lastIndex) was recorded and whether the word atlastIndexis different from the current one, or it is the same (in scenarios wherew1equalsw2). - If the conditions hold true, it updates
minDistto the minimum value between the storedminDistand the difference betweenidxandlastIndex. lastIndexis then set to the currentidx.
- If the current word matches
- Finally, the function returns
minDist, representing the shortest distance between the occurrences ofw1andw2.
This approach ensures that the solution is efficient with a time complexity of O(n), where n is the length of the dictionary, as it processes each word sequentially and performs minimal operations per word. The space complexity is O(1) since it only uses a few additional variables regardless of the input size.
- Java
class Solution {
public int findMinDistance(String[] wordsArray, String firstWord, String secondWord) {
int minDistance = Integer.MAX_VALUE;
int lastIndex = -1;
for (int index = 0; index < wordsArray.length; index++) {
if (wordsArray[index].equals(firstWord) || wordsArray[index].equals(secondWord)) {
if (lastIndex != -1 && (!wordsArray[lastIndex].equals(wordsArray[index]) || firstWord.equals(secondWord))) {
minDistance = Math.min(minDistance, index - lastIndex);
}
lastIndex = index;
}
}
return minDistance;
}
}
The Java solution provided aims to find the minimum distance between two given words in an array of words, where the same word can also be queried for its closest repeat. The function findMinDistance accepts an array of strings (wordsArray), and two strings (firstWord and secondWord) representing the words for which the distance is to be calculated.
Here’s a breakdown of how the logic is implemented:
- Initialize
minDistancewithInteger.MAX_VALUEto track the smallest distance found. - Use
lastIndexinitialized to-1to store the index of the last found target word. - Iterate through the
wordsArrayusingindex. - Check if the current word is either
firstWordorsecondWord. - If
lastIndexis not-1and either the last word is not the same as the current word (i.e., searching for the distance between different words) or when both target words are the same (i.e., finding the shortest distance between repeats of the same word), updateminDistancewith the smaller value between the previously recordedminDistanceand the difference betweenindexandlastIndex. - Update
lastIndexto the currentindex. - After looping through the array, return
minDistance.
This simple yet effective approach handles cases where both target words are the same or different, efficiently determining the shortest distance in a single pass through the array, making it optimal for scenarios where the word list is large or dynamic.