⚡Flashcard Drill➔
NeetCode #158LC-244MediumArrays & Hashing
← Back to All Problems

#158 · #244 · Shortest Word Distance II(最短单词距离 II)

📌 Problem Statement & Constraints

Design a class that is initialised with an array of strings wordsDict and answers repeated queries shortest(word1, word2) returning the shortest distance between the two words. Constraints: 1 <= wordsDict.length <= 3 * 10^4; up to 10^4 queries.

💡 Core Algorithmic Approaches

  1. Precompute a map from word to the sorted list of its indices. Preprocessing is O(n).
  2. Each query is then a merge of two sorted index lists, which is O(k1 + k2).
  3. Advance the pointer whose index is smaller, since the other list's next element can only be closer.
  4. This is the standard two-pointer merge on sorted lists and avoids re-scanning the whole array per query.

💻 Benchmark Python3 Implementation

class WordDistance:
    def __init__(self, wordsDict: List[str]):
        from collections import defaultdict
        self.pos = defaultdict(list)
        for i, w in enumerate(wordsDict):
            self.pos[w].append(i)          # sorted by construction

    def shortest(self, word1: str, word2: str) -> int:
        a, b = self.pos[word1], self.pos[word2]
        i = j = 0
        best = float("inf")
        while i < len(a) and j < len(b):
            best = min(best, abs(a[i] - b[j]))
            if a[i] < b[j]:                # advance the smaller index
                i += 1
            else:
                j += 1
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) preprocessing, then O(k1 + k2) per query where k1, k2 are the occurrence counts of the two words.
💾 Space Complexity
O(n) for the index lists.

⚠️ Interview Pitfalls & Follow-ups

  • Re-scanning the array per query: O(n) per query, i.e. O(n * q) overall, which is far too slow for 10^4 queries.
  • Advancing both pointers: the merge would skip candidate pairs; advance only the smaller index.
  • Sorting the index lists at query time: they are built in increasing order, so no sort is needed.
  • Assuming the two words differ: the class supports the same word twice, in which case the answer is the minimum gap between consecutive occurrences.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

最短单词距离 II

请设计一个类,使该类的构造函数能够接收一个字符串数组 wordsDict。这个类将有一个方法 shortest(word1, word2) ,该方法将返回在 wordsDict 中 word1 和 word2 之间的最短距离。多次调用该方法时,你可以假设 word1 != word2。约束:1 ≤ wordsDict.length ≤ 3 × 10^4;1 ≤ word1.length, word2.length ≤ 10;word1 != word2;最多调用 10^4 次 shortest。

核心要点

  • 预处理「单词 → 下标列表」(标准解) :构造函数中把每个单词出现的所有下标收集成列表。
  • 双指针求最近距离 : shortest 时对两个有序下标列表用双指针——比较当前两个下标,把较小的那个指针右移,同时更新最小差值。
  • 为什么双指针是对的 :两个列表均升序。设 a[i] &lt; b[j],则 a[i] 与 b[j] 之后的任何元素距离都更大,因此可以安全地推进 i。
  • 为什么必须预处理 :若每次 shortest 都扫描整个 wordsDict,单次是 O(n);预处理后单次是 O(k1 + k2),k 为出现次数,通常远小于 n。

常见陷阱

  • 每次 shortest 都重新扫描 wordsDict :单次 O(n),q 次调用总代价 O(q · n),可能超时。预处理是本题的设计意图。
  • 双指针推进较大者 :必须推进 较小 的下标,才能让两个指针靠近。推进较大者会让距离增大,永远找不到最小。
  • 用 abs() 比较 :由于列表升序,实际上两个指针的大小关系决定了距离符号,用 abs 或直接相减都可;但用 abs 更直观。
  • 用集合存下标 :集合无序,无法用双指针求最近距离。必须用有序列表。

参考实现

from collections import defaultdict

class WordDistance:
    def __init__(self, wordsDict: list[str]):
        self.pos = defaultdict(list)          # 单词 -> 升序的下标列表
        for i, w in enumerate(wordsDict):
            self.pos[w].append(i)

    def shortest(self, word1: str, word2: str) -> int:
        a, b = self.pos[word1], self.pos[word2]
        i = j = 0
        best = float('inf')
        while i < len(a) and j < len(b):
            best = min(best, abs(a[i] - b[j]))
            if a[i] < b[j]:                   # 推进较小者,才可能缩小距离
                i += 1
            else:
                j += 1
        return best