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:
- Iterate through the words list and store every instance of word1 and word2 in their owns separate lists.
- For every value in word1_instances, loop over every value in word2_instances and record the smallest difference.
- 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)
Here’s the code that solves this problem: