def shortest_word_distance(words, word1, word2):
    word1_indices, word2_indices = [], []
    for i, word in enumerate(words):
        if word == word1:
            word1_indices.append(i)
        elif word == word2:
            word2_indices.append(i)
    return min_distance(word1_indices, word2_indices)


def min_distance(list1, list2):
    best_dist = abs(list1[0] - list2[0])
    i = j = 0
    while i < len(list1) and j < len(list2):
        best_dist = min(best_dist, abs(list1[i]-list2[j]))
        if best_dist == 1:
            break
        if list1[i] < list2[j]:
            i += 1
        else:
            j += 1
    return best_dist

https://leetcode.com/problems/two-sum/

results matching ""

    No results matching ""