Minimum index distance between two given words in a word list
LinkedInSoftware Engineer · Technical ScreenLast updated
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.
Given a list of words and two different words that both occur in it, return the smallest distance between a position of the first word and a position of the second word. The distance between positions i and j is |i - j|.
Function Signature
def shortest_word_distance(words: list[str], word1: str, word2: str) -> int:
words is the list to search; word1 and word2 are the two words to measure between.
Rules
- Positions are indices into
words. Either word may occur several times; consider every pair made of one occurrence ofword1and one occurrence ofword2, and return the smallest distance among them. - The answer does not depend on the order in which
word1andword2are given.
Constraints
2 <= len(words) <= 10^5- Each word consists of 1 to 20 lowercase English letters
word1 != word2, and both occur inwordsat least once
Examples
Example 1
Input: words = ["apple", "kiwi", "pear", "plum", "apple", "fig"], word1 = "pear", word2 = "fig"
Output: 3
pear is at index 2 and fig at index 5, so the distance is 3.
Example 2
Input: words = ["red", "green", "blue", "yellow", "green", "red"], word1 = "yellow", word2 = "red"
Output: 2
yellow is at index 3 and red is at indices 0 and 5. The closer occurrence is at index 5, at distance 2.
Example 3
Input: words = ["a", "b"], word1 = "b", word2 = "a"
Output: 1
The words are adjacent; listing word1 after word2 in the input does not change the answer.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.