
Problem Statement
In this problem, you are given an array of strings denoted as wordsDict
, and two distinct strings word1
and word2
which are guaranteed to be present in wordsDict
. Your task is to find the shortest distance between word1
and word2
in the given list. The distance is measured as the number of words between word1
and word2
including one of them but excluding the other.
Examples
Example 1
Input:
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output:
3
Example 2
Input:
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output:
1
Constraints
2 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i]
consists of lowercase English letters.word1
andword2
are inwordsDict
.word1 != word2
Approach and Intuition
When approaching this problem, it's important to understand that we are looking for the minimal distance between two specific words in an array. Our goal is not just to find the words but to measure how closely they occur within the array.
Here is a step-by-step method to solve this:
Initialize two variables,
index1
andindex2
, to store the latest occurrences ofword1
andword2
. Set them to some initial value that indicates they haven't been found yet (for example, -1).Iterate through the
wordsDict
from the first to the last element. For each word:- If the word matches
word1
, updateindex1
to the current index. - If the word matches
word2
, updateindex2
to the current index.
- If the word matches
After updating either
index1
orindex2
, check if bothindex1
andindex2
have been updated from their initial values (i.e., both words have been found at least once).If the above condition is true, compute the distance as the absolute difference between
index1
andindex2
. Keep track of the minimum of such distances observed during the iteration.
The above approach works effectively because:
It runs in a single pass through
wordsDict
, hence it is efficient with a time complexity of O(n) where n is the number of words inwordsDict
.By continually updating the positions of
word1
andword2
, and calculating the distance immediately when both have been found, we ensure that the minimum distance is accurately captured, regardless of how many times the words appear in the dictionary.
This method is direct and takes advantage of the sequential nature of lists, utilizing the indices to calculate distances between elements. It efficiently narrows down the computation to necessary cases, ignoring all positions of the array that do not pertain to word1
or word2
.
Solutions
- Java
class Solution {
public int findMinDistance(String[] wordsDict, String firstWord, String secondWord) {
int pos1 = -1, pos2 = -1;
int shortestDistance = wordsDict.length;
for (int idx = 0; idx < wordsDict.length; idx++) {
if (wordsDict[idx].equals(firstWord)) {
pos1 = idx;
} else if (wordsDict[idx].equals(secondWord)) {
pos2 = idx;
}
if (pos1 != -1 && pos2 != -1) {
shortestDistance = Math.min(shortestDistance, Math.abs(pos1 - pos2));
}
}
return shortestDistance;
}
}
The provided Java code defines a method, findMinDistance
, to determine the smallest distance between two specified words in an array of words. The method accomplishes this using the following approach:
- Initialize two variables
pos1
andpos2
to -1, which store the positions offirstWord
andsecondWord
in the array, respectively. - Use the variable
shortestDistance
to record the minimum distance, initializing it with the length of the array, which is the maximum distance it could possibly be. - Iteratively traverse through the
wordsDict
array using a for loop:- If the current word matches
firstWord
, updatepos1
to the current index. - If it matches
secondWord
, updatepos2
to the current index. - After updating positions, if both
pos1
andpos2
are updated from their initial values (-1), compute the absolute difference between the two indices and updateshortestDistance
if this distance is less than the previously recorded shortest distance.
- If the current word matches
- Finally, return the value of
shortestDistance
, which will be the minimum distance found between the two words.
This solution is efficient because it finds the minimum distance in a single pass through the array, ensuring an O(n) time complexity where n is the number of words in the array. This makes the solution ideal for scenarios where one needs to quickly find distances in large word lists.
No comments yet.