243. Shortest Word Distance
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
This problem asks for the shortest distance between two specific words in an array of strings. The distance is defined as the absolute difference of their indices. Since we need to find the minimum distance, this suggests we should compare all possible pairs of occurrences of word1 and word2. However, a more efficient approach is to iterate through the array just once.
Solution
Shortest Word Distance in Python
class Solution:
def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
idx1 = -1 # Tracks the most recent index of word1
idx2 = -1 # Tracks the most recent index of word2
min_distance = float('inf') # Initialize with a very large value
for i, word in enumerate(wordsDict):
if word == word1:
idx1 = i
elif word == word2:
idx2 = i
# Once both words have been found at least once,
# calculate the distance and update the minimum.
# Since we iterate sequentially, idx1 and idx2 will always hold
# the indices of the most recent occurrences of word1 and word2.
if idx1 != -1 and idx2 != -1:
min_distance = min(min_distance, abs(idx1 - idx2))
return min_distance
Shortest Word Distance in Java
class Solution {
public int shortestDistance(String[] wordsDict, String word1, String word2) {
int idx1 = -1; // Tracks the most recent index of word1
int idx2 = -1; // Tracks the most recent index of word2
int minDistance = Integer.MAX_VALUE; // Initialize with a very large value
for (int i = 0; i < wordsDict.length; i++) {
if (wordsDict[i].equals(word1)) {
idx1 = i;
} else if (wordsDict[i].equals(word2)) {
idx2 = i;
}
// Once both words have been found at least once,
// calculate the distance and update the minimum.
// Since we iterate sequentially, idx1 and idx2 will always hold
// the indices of the most recent occurrences of word1 and word2.
if (idx1 != -1 && idx2 != -1) {
minDistance = Math.min(minDistance, Math.abs(idx1 - idx2));
}
}
return minDistance;
}
}
Shortest Word Distance in C++
class Solution {
public:
int shortestDistance(vector<string>& wordsDict, string word1, string word2) {
int idx1 = -1; // Tracks the most recent index of word1
int idx2 = -1; // Tracks the most recent index of word2
int minDistance = INT_MAX; // Initialize with a very large value
for (int i = 0; i < wordsDict.size(); ++i) {
if (wordsDict[i] == word1) {
idx1 = i;
} else if (wordsDict[i] == word2) {
idx2 = i;
}
// Once both words have been found at least once,
// calculate the distance and update the minimum.
// Since we iterate sequentially, idx1 and idx2 will always hold
// the indices of the most recent occurrences of word1 and word2.
if (idx1 != -1 && idx2 != -1) {
minDistance = min(minDistance, abs(idx1 - idx2));
}
}
return minDistance;
}
};
Shortest Word Distance in TypeScript
function shortestDistance(wordsDict: string[], word1: string, word2: string): number {
let idx1: number = -1; // Tracks the most recent index of word1
let idx2: number = -1; // Tracks the most recent index of word2
let minDistance: number = Infinity; // Initialize with a very large value
for (let i = 0; i < wordsDict.length; i++) {
const word = wordsDict[i];
if (word === word1) {
idx1 = i;
} else if (word === word2) {
idx2 = i;
}
// Once both words have been found at least once,
// calculate the distance and update the minimum.
// Since we iterate sequentially, idx1 and idx2 will always hold
// the indices of the most recent occurrences of word1 and word2.
if (idx1 !== -1 && idx2 !== -1) {
minDistance = Math.min(minDistance, Math.abs(idx1 - idx2));
}
}
return minDistance;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.