Ctrl K

Two Words, Closest Apart

Easy
You are given a list of words words and two different words first and second, each appearing in the list at least once (possibly several times). The distance between positions i and j is |i - j|. Return the smallest distance between any position holding first and any position holding second.
Example 1
words=['red', 'green', 'blue', 'red', 'yellow', 'blue'], first='red', second='blue' → 1

"red" is at positions 0 and 3, "blue" at 2 and 5. The closest pair is 3 and 2, one step apart.

Example 2
words=['cat', 'dog', 'fox', 'owl'], first='owl', second='cat' → 3

Each word appears once, at positions 3 and 0, so the distance is 3.

Constraints
  • 2 ≤ len(words) ≤ 3 · 10⁴
  • 1 ≤ length of each word ≤ 10
  • Words consist of lowercase English letters
  • first and second both occur in words
  • first ≠ second
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsOne-Row Typing EasyDinner for Two EasyPhrases with Synonyms EasyWord from a License Plate EasyDistinct Morse Signals Easy
loading Python…
Input
words=['red', 'green', 'blue', 'red', 'yellow', 'blue'], first='red', second='blue'
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.