KatInterview

Closest Pair of Target Words

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashingarraystringsingle-pass

Last 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.