Shortest Word Distance II

Repeated distance queries over a fixed word list — preprocess word to sorted index list, two-pointer merge per query.

Medium
Time O(n) init Space O(n)
LeetCode
4 min read
design hash-map two-pointers

Problem#

Given a list of strings, support repeated shortest(word1, word2) queries returning the minimum index distance between any occurrence of the two words.

Examples#

  • ["practice","makes","perfect","coding","makes"]; shortest("coding","practice")3.
  • shortest("makes","coding")1.

Constraints#

  • 1 <= wordsDict.length <= 3 * 10^4, up to 5000 queries.

Approach#

In the constructor, build unordered_map<string, vector<int>> of each word to its sorted occurrence indices. Each query two-pointer merges the two lists, tracking the minimum positive index gap.

Solution#

Shortest Word Distance II
class WordDistance {
unordered_map<string, vector<int>> pos;
public:
WordDistance(vector<string>& wordsDict) {
for (int i = 0; i < (int)wordsDict.size(); ++i)
pos[wordsDict[i]].push_back(i);
}
int shortest(string word1, string word2) {
auto& a = pos[word1];
auto& b = pos[word2];
int i = 0, j = 0, ans = INT_MAX;
while (i < (int)a.size() && j < (int)b.size()) {
ans = min(ans, abs(a[i] - b[j]));
if (a[i] < b[j]) ++i; else ++j;
}
return ans;
}
};

Editorial#

Because both index lists are sorted, advancing the smaller pointer is the optimal move — any further increment of the larger one will only widen the gap. Total work per query is linear in the sum of occurrence counts, far better than rescanning the whole array.

Complexity#

  • Time: O(n) init, O(a + b) per query.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.