Shortest Word Distance II Problem
Description
LeetCode Problem 244.
Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the WordDistance class:
WordDistance(String[] wordsDict)initializes the object with the strings arraywordsDict.int shortest(String word1, String word2)returns the shortest distance betweenword1andword2in the arraywordsDict.
Example 1:
Input
["WordDistance", "shortest", "shortest"]
[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
Output
[null, 3, 1]
Explanation
WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
wordDistance.shortest("coding", "practice"); // return 3
wordDistance.shortest("makes", "coding"); // return 1
Constraints:
1 <= wordsDict.length <= 3 * 10^41 <= wordsDict[i].length <= 10wordsDict[i]consists of lowercase English letters.word1andword2are inwordsDict.word1 != word2- At most
5000calls will be made toshortest.
Solution
Approach: Index Lists + Two Pointers
With many queries on the same list, scanning the whole list each time is wasteful. Instead, in the constructor store, for each word, the list of indices where it appears. These lists are built in one pass, so each is already sorted.
For shortest(word1, word2), take the two index lists a and b and walk them with two pointers, like the merge step of merge sort. At each step, compare abs(a[i] - b[j]) with the best so far, then move the pointer that points at the smaller index.
Why is it safe to move that one? Say a[i] < b[j]. Every later index in b is even larger than b[j], so pairing a[i] with any of them only gives a larger distance. a[i] has no better partner left, and we can drop it.
Complexity: O(n) time for the constructor. O(p + q) time per query, where p and q are the numbers of occurrences of the two words. O(n) space for the index lists.
from collections import defaultdict
class WordDistance:
def __init__(self, wordsDict: List[str]):
self.positions = defaultdict(list) # word -> its indices, in increasing order
for i, w in enumerate(wordsDict):
self.positions[w].append(i)
def shortest(self, word1: str, word2: str) -> int:
a, b = self.positions[word1], self.positions[word2]
ans = float("inf")
i = j = 0
while i < len(a) and j < len(b):
ans = min(ans, abs(a[i] - b[j]))
# Move the smaller index: pairing it with anything later in the other list is only farther.
if a[i] < b[j]:
i += 1
else:
j += 1
return ans
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)