clueless coding // TODO: be smarter

LeetCode Shortest Word Distance II: CPP Solution



TL;DR Code Solution



unordered_map<string, vector<int>> map;

WordDistance(vector<string> words) {
    for (int i = 0; i < words.size(); i++) {
        map[words[i]].push_back(i);
    }
}

int shortest(string word1, string word2) {
    int i = 0; int j = 0;
    int result = INT_MAX;
    while (i < map[word1].size() && j < map[word2].size()) {
        result = min(abs(map[word1][i] - map[word2][j]), result);
        if (map[word1][i] < map[word2][j]) {
            i++;
        }
        else {
            j++;
        }
    }


    return result;
}