Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Last active December 1, 2020 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuntalchandra/2b989362be5dd096a013d9492c44eeab to your computer and use it in GitHub Desktop.
Save kuntalchandra/2b989362be5dd096a013d9492c44eeab to your computer and use it in GitHub Desktop.
Shortest Word Distance
"""
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
"""
class Solution:
def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
pos_1 = pos_2 = -1
distance = len(words)
for idx, word in enumerate(words):
if words[idx] == word1:
pos_1 = idx
elif words[idx] == word2:
pos_2 = idx
if pos_1 != -1 and pos_2 != -1:
distance = min(abs(pos_2 - pos_1), distance)
return distance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment