Answer Repeated Shortest Word Distance Queries
LinkedInSoftware Engineer · Technical ScreenLast updated
Design a data structure that preprocesses a list of words to efficiently answer repeated queries for the shortest index distance between two distinct words.
Problem Statement
Design a class that accepts an array of strings and supports repeated queries to find the minimum distance between two distinct words in the array.
The distance between two words at indices i and j is defined as abs(i - j).
Implement the WordDistance class:
WordDistance(words: list[str]): Initializes the object with the array of stringswords.shortest(word1: str, word2: str) -> int: Returns the minimum distance betweenword1andword2in the original array.
Matching is case-sensitive. Both word1 and word2 are guaranteed to exist in words and will always be distinct.
Function Interface
class WordDistance:
def __init__(self, words: list[str]):
pass
def shortest(self, word1: str, word2: str) -> int:
pass
Examples
Example 1
Input:
wd = WordDistance(["practice", "makes", "perfect", "coding", "makes"])
wd.shortest("coding", "practice")
wd.shortest("makes", "coding")
Output:
3
1
Explanation:
- "coding" is at index 3 and "practice" is at index 0. The distance is abs(3 - 0) = 3.
- "makes" appears at indices 1 and 4, while "coding" is at index 3. The minimum distance is min(abs(1 - 3), abs(4 - 3)) = min(2, 1) = 1.
Constraints
1 <= len(words) <= 300001 <= len(words[i]) <= 10words[i]consists of lowercase and uppercase English letters.word1andword2are distinct and guaranteed to exist inwords.- At most
5000calls will be made toshortest.
Edge Cases
- The minimum distance is
1when the two words appear as immediate neighbors. - One word may appear once while the other appears many times across the array.
- The earliest occurrences might not yield the shortest distance; all relative pairs must be evaluated.
Hints
Hint 1
During initialization, store all indices of each word in a hash map mapping each string to a sorted list of its positions.
Hint 2
For each query, retrieve the two sorted index lists and use a two-pointer approach to find the minimum difference.
Hint 3
At each step in the two-pointer scan, compute the distance and advance the pointer pointing to the smaller index.
Follow-up questions
- If one word appears thousands of times while the other appears only once or twice, how could you optimize the two-pointer scan using binary search?
- How would you add an LRU cache or memoization strategy to speed up repeated queries for the exact same pair of words?
- How would the logic change if word1 and word2 could be identical, meaning you need the shortest distance between two different occurrences of the same word?
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.