Shortest Word Distance — LeetCode

This is the first problem for the LeetCode December challenge. This one took me longer than I’d like to admit. Here’s the problem:

Algorithmically, you must:

  1. Iterate through the words list and store every instance of word1 and word2 in their owns separate lists.
  2. For every value in word1_instances, loop over every value in word2_instances and record the smallest difference.
  3. Return the min_difference

Expanding on step 2, the logic looks something like this:

min_dif = 999999
for i in word1_instances:
for j in word2_instances:
if abs(i - j) < min_diff:
min_diff = abs(i - j)
return min_diff

Here’s the code that solves this problem: