Minimum index distance between two given words in a word list
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Overview: Coding problem: given a list of words and two different target words that both appear in it, return the smallest distance between an index of one word and an index of the other. It tests single-pass scanning with position tracking, handling of repeated occurrences, and time complexity analysis.
Read the full LinkedIn Software Engineer interview experience this question came from
Constraints
- 2 <= len(words) <= 10^5
- Each word in words consists of 1 to 20 lowercase English letters
- word1 != word2, and both occur in words at least once
- The answer is between 1 and len(words) - 1, so it never exceeds 2^31 - 1 (a 32-bit int suffices in every language)
Examples
Input: (['apple', 'kiwi', 'pear', 'plum', 'apple', 'fig'], 'pear', 'fig')
Expected Output: 3
Explanation: Source Example 1: pear is at index 2 and fig at index 5; the apple occurrences are ignored.
Input: (['red', 'green', 'blue', 'yellow', 'green', 'red'], 'yellow', 'red')
Expected Output: 2
Explanation: Source Example 2: yellow is at index 3 and red at indices 0 and 5; the later red is closer, at distance 2.
Hints
- Every pair made of one occurrence of word1 and one occurrence of word2 is a candidate, and either word may occur many times.
- The answer must not change if word1 and word2 are swapped, so an occurrence of word2 before word1 matters just as much as one after it.
- With up to 10^5 words, consider whether you really need to compare every occurrence of one word with every occurrence of the other.