Find the minimum distance between word 1 and word 2 in the list of words.
Create two "trackers", idx_1 and idx_2: idx_1 keeps track of where the first word appears in the list, and idx_2 keeps track of where the second word appears in the list. Go through each word in the list one by one. If the current word matches the first word, update idx_1 with its position. If the current word matches the second word, update idx_2 with its position. Once we have the positions of both words (idx_1 and idx_2), we calculate how far apart they are in the list. We repeat steps for the entire list to find the smallest distance between the two words.
word1 = 'the' word2 = 'fox' ls = ['the', 'quick', 'brown', 'fox', 'quick'] output = float('inf') idx1 = -1 idx2 = -1 for i in range(len(ls)): w = ls[i] if w == word1: idx1 = i if w == word2: idx2 = i if idx1 != -1 and idx2 != -1: output = min(output, abs(idx1 - idx2)) print(output)
const word1 = 'the'; const word2 = 'fox'; const list = ['the', 'quick', 'brown', 'fox', 'quick']; let output = Infinity; let idx1 = -1; let idx2 = -1 for (let i = 0; i < list.length; i++) { let w = list[i]; if (w === word1) { idx1 = i; } if (w === word2) { idx2 = i; } if (idx1 !== -1 && idx2 !== -1) { output = Math.min(output, Math.abs(idx1 - idx2)); } } console.log(output);