Shortest Word Distance — LeetCode 243 Python Solution
- Problem
- #243
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.
Example
- Input
- wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
- Output
- 3
Python solution
class Solution:
def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
i = j = -1
ans = inf
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) |
| Space | O(1) to O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 243. Shortest Word Distance 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 243. Shortest Word Distance?
- LeetCode 243. Shortest Word Distance is rated Easy on LeetCode.
- What topics does LeetCode 243. Shortest Word Distance cover?
- LeetCode 243. Shortest Word Distance is tagged Array and String on LeetCode.
- Is LeetCode 243. Shortest Word Distance a premium problem?
- Yes. LeetCode 243. Shortest Word Distance is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.