Closest Pair of Target Words
Arrays & HashingAuto-graded · 19 test casesLast updated
Find the minimum index gap between any occurrence of two distinct words in a list using single-pass tracking.
You are given a list of words and two distinct target words that both appear somewhere in the list. Your task is to find the smallest index gap between any occurrence of the first target and any occurrence of the second target.
The gap between indices i and j is defined as |i - j|.
Write a function that takes the word list and the two target words, and returns the minimum gap.
Rules
- Both target words are guaranteed to appear at least once in the list.
- Either or both words may appear multiple times. You must consider all possible pairings: take one occurrence of the first target and one occurrence of the second target, compute their gap, and return the smallest such gap across all pairings.
- The two target words are distinct (never equal).
- The result does not depend on which target is passed first or second.
Constraints
2 <= len(words) <= 10^5- Each word in the list contains 1 to 20 lowercase English letters.
- The two target words are different and both exist in the list.
Examples
Example 1
Input: closest_word_pair(['apple', 'kiwi', 'pear', 'plum', 'apple', 'fig'], 'pear', 'fig')
Output: 3
Example 2
Input: closest_word_pair(['red', 'green', 'blue', 'yellow', 'green', 'red'], 'yellow', 'red')
Output: 2
Example 3
Input: closest_word_pair(['a', 'b'], 'b', 'a')
Output: 1
Hints
Hint 1
You don't need to store all positions of each word—just remember the most recent position you've seen for each target.
Hint 2
Every time you encounter one of the targets, check if you've already seen the other target. If so, compute the gap and update your answer.
Hint 3
A single left-to-right scan is sufficient. The closest occurrence of the other word is always the most recent one you've passed.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Traverse the word list once from left to right while maintaining two variables: the most recently seen index of each target word. Initially, both indices are unset (we can use -1 as a sentinel).
As you scan:
- When you encounter the first target, update its tracked position.
- When you encounter the second target, update its tracked position.
- After updating either position, if both positions are valid (both have been seen), compute the absolute gap between them and update the running minimum.
This works because for any occurrence of one target, the closest occurrence of the other target to its left is always the most recent one encountered so far. When you reach a new occurrence of either target, you immediately check against the latest occurrence of the other target, ensuring no optimal pair is missed.
The algorithm is symmetric: swapping the two targets only swaps the roles of the two position trackers, but the absolute gap remains the same.
Why It Works
Consider any optimal pair of indices (a, b) where a < b, one holding the first target and the other holding the second. When the scan reaches position b, the tracker for the other word holds some index a' where a' >= a (the most recent occurrence up to b). Since a' is at least as close to b as a is, the gap computed at position b is at most the optimal gap. Because we track the minimum across the entire scan, we capture the true optimum.
We initialize the minimum gap to len(words), which is larger than any possible index difference, ensuring it gets replaced by the first valid gap encountered.
Complexity
- Time: O(n), where n is the length of the word list. We make one pass through the list, and string comparisons take constant time given the bounded word length (≤ 20 characters).
- Space: O(1) additional space. We only store two indices and one integer for the running minimum.
Solution
from typing import List
def closest_word_pair(words: List[str], target1: str, target2: str) -> int:
pos1 = pos2 = -1
min_gap = len(words)
for i, word in enumerate(words):
if word == target1:
pos1 = i
elif word == target2:
pos2 = i
else:
continue
if pos1 >= 0 and pos2 >= 0:
gap = abs(pos1 - pos2)
if gap < min_gap:
min_gap = gap
return min_gap