Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
// Brute force
int shortestDistance(vector<string>& words, string word1, string word2) { // time: O(n^2); space: O(1)
if (words.empty()) return 0;
int n = words.size(), res = INT_MAX;
for (int i = 0; i < n; ++i) {
if (words[i] != word1) continue;
for (int j = 0; j < n; ++j) {
if (words[j] != word2) continue;
res = min(res, abs(i - j));
}
}
return res;
}
// Optimized time method
int shortestDistance(vector<string>& words, string word1, string word2) { // time: O(n); space: O(1)
int idx1 = -1, idx2 = -1, res = words.size();
for (int i = 0; i < words.size(); ++i) {
if (words[i] == word1) {
idx1 = i;
}
if (words[i] == word2) {
idx2 = i;
}
if (idx1 != -1 && idx2 != -1) {
res = min(res, abs(idx1 - idx2));
}
}
return res;
}
// Optimized time method
int shortestDistance(vector<string>& words, string word1, string word2) { // time: O(n); space: O(1)
int idx = -1, res = words.size();
for (int i = 0; i < words.size(); ++i) {
if (words[i] == word1 || words[i] == word2) {
if (idx != -1 && words[idx] != words[i]) {
res = min(res, i - idx);
}
idx = i;
}
}
return res;
}