[
string
two pointers
array
]
Leetcode 0243 Shortest Word Distance
Problem statement
https://leetcode.com/problems/shortest-word-distance/
Solution
Go from left to right and keep two pointers: for each of two words. Update them if new word equal to word1
or word2
.
Complexity
Time complexity is $O(n)$ and space complexity is $O(1)$.
Code
class Solution:
def shortestDistance(self, wordsDict, word1, word2):
p1, p2 = -float("inf"), float("inf")
ans = p2 - p1
for i, word in enumerate(wordsDict):
if word == word1:
p1 = i
ans = min(ans, abs(p2 - p1))
if word == word2:
p2 = i
ans = min(ans, abs(p2 - p1))
return ans