Shortest Word Distance III — LeetCode 245 Python Solution
- Problem
- #245
- Pattern
- Hash Map
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list. Note that word1 and word2 may be the same.
Example
- Input
- wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
- Output
- 1
Python solution
class Solution:
def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
ans = len(wordsDict)
if word1 == word2:
j = -1
for i, w in enumerate(wordsDict):
if w == word1:
if j != -1:
ans = min(ans, i - j)
j = i
else:
i = j = -1
for k, w in enumerate(wordsDict):
if w == word1:
i = k
if w == word2:
j = k
if i != -1 and j != -1:
ans = min(ans, abs(i - j))
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{wordsDict} |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 245. Shortest Word Distance III is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 245. Shortest Word Distance III?
- LeetCode 245. Shortest Word Distance III is rated Medium on LeetCode.
- What is the time complexity of LeetCode 245. Shortest Word Distance III?
- The Python solution on this page runs in O(n), where n is the length of the array \textit{wordsDict}.
- What is the space complexity of LeetCode 245. Shortest Word Distance III?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 245. Shortest Word Distance III cover?
- LeetCode 245. Shortest Word Distance III is tagged Array and String on LeetCode.
- Is LeetCode 245. Shortest Word Distance III a premium problem?
- Yes. LeetCode 245. Shortest Word Distance III is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.