Simply store indices in ctor.
class WordDistance { unordered_map<string, vector<int>> hm; public: WordDistance(vector<string>& words) { for (int i = 0; i < words.size(); i++) { hm[words[i]].push_back(i); } } int shortest(string word1, string word2) { vector<int> &vec1 = hm[word1]; vector<int> &vec2 = hm[word2]; int ret = INT_MAX; int i1 = 0, i2 = 0; while (i1 < vec1.size() && i2 < vec2.size()) { int v1 = vec1[i1], v2 = vec2[i2]; ret = std::min(ret, abs(v1 - v2)); if (v1 < v2) i1++; else i2++; } return ret; } };