A variation of linear scan..
typedef pair<int, bool> Rec; class Solution { public: int shortestDistance(vector<string>& words, string word1, string word2) { vector<Rec> recs; int ret = INT_MAX; for (int i = 0; i < words.size(); i++) { bool bFound = false; if (words[i] == word1){ bFound = true; recs.push_back(Rec(i, true)); } if (words[i] == word2){ bFound = true; recs.push_back(Rec(i, false)); } if (bFound) { size_t len = recs.size(); if (recs.size() > 1) { if (recs[len - 1].second != recs[len - 2].second) { int cur = recs[len - 1].first - recs[len - 2].first; ret = std::min(cur, ret); } } } } return ret; } };