NeetCode #89LC-243EasyArrays & Hashing
← Back to All Problems#89 · #243 · Shortest Word Distance(最短单词距离)
📌 Problem Statement & Constraints
Given an array of strings
wordsDict and two different strings word1 and word2, return the shortest distance between any occurrence of word1 and any occurrence of word2. Constraints: 1 <= wordsDict.length <= 3 * 10^4, word1 != word2, both guaranteed to appear.💡 Core Algorithmic Approaches
- A single pass suffices: remember the most recent index where
word1was seen and whereword2was seen. - Whenever both have been seen, the gap
|i - j|is a candidate answer. - Keeping only the most recent index of each word is sufficient, because an older occurrence can only produce a larger distance.
- This avoids collecting all indices and comparing every cross pair, which would be O(k1 * k2).
💻 Benchmark Python3 Implementation
class Solution:
def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
i = j = -1 # most recent positions
best = float("inf")
for k, w in enumerate(wordsDict):
if w == word1:
i = k
elif w == word2:
j = k
if i != -1 and j != -1:
best = min(best, abs(i - j))
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two indices.
⚠️ Interview Pitfalls & Follow-ups
- Collecting all indices and taking the cross-product minimum: O(k1 * k2) and unnecessary.
- Using
elifincorrectly when the two words can be equal: the problem guaranteesword1 != word2, soelifis safe here. The general variant with possibly-equal words would need two separateifs. - Forgetting to check that both have been seen:
abs(-1 - k)would produce a spurious large distance.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
最短单词距离
给定一个字符串数组 wordsDict 和两个字符串 word1 和 word2,返回这两个单词在列表中的 最短距离 。距离定义为两个单词下标之差的绝对值。约束:1 ≤ wordsDict.length ≤ 3 × 10^4;1 ≤ word1.length, word2.length ≤ 10;word1 != word2;两个单词都在 wordsDict 中出现。
核心要点
- 一次遍历记录最近位置(标准解) :维护 word1 与 word2 最近一次出现的下标 i1、i2。每遇到其中一个单词就更新对应下标,并计算当前距离更新答案。
- 为什么只需比较最近一次 :数组是线性扫描的,任何更早的出现都只会让距离更大,因此只需保留「最近一次」。
- 为什么不用先收集所有位置 :收集所有下标列表再两两比较是 O(k1 × k2),而一次遍历是 O(n)。
- 初值处理 :i1、i2 初始为 −1,只有两者都非 −1 时才计算距离。
常见陷阱
- 用 if w == word1 ... if w == word2 而非 elif :题目保证 word1 != word2,因此两种写法等价;但用 elif 更清晰地表达「一个位置只可能是一个单词」。
- 先收集所有位置再两两比较 :O(k1 × k2) 在极端情况下(两个单词各出现 n/2 次)退化为 O(n²)。
- 忘记 i1 != -1 and i2 != -1 的判断 :未同时找到两个单词时计算距离会得到错误的巨大值。
参考实现
class Solution:
def shortestDistance(self, wordsDict: list[str], word1: str, word2: str) -> int:
i1 = i2 = -1
best = len(wordsDict)
for i, w in enumerate(wordsDict):
if w == word1:
i1 = i
elif w == word2:
i2 = i
if i1 != -1 and i2 != -1:
best = min(best, abs(i1 - i2))
return best