Last active
December 1, 2020 14:56
-
-
Save kuntalchandra/2b989362be5dd096a013d9492c44eeab to your computer and use it in GitHub Desktop.
Shortest Word Distance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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