Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Shortest Word Distance (easy)
.....
.....
.....
Like the course? Get enrolled and start learning!
A
Anonymous
· 2 years ago
How to solve if the words can be same and we want to find the distance between them.
A
Anonymous
· 3 years ago
Any suggestions for further practice on this type of problem?
A
Anonymous
· 3 years ago
class Solution: def shortestDistance(self, words, word1, word2): # TODO: Write your code here # Find index of word1 and word 2 in words array # when we update the indexes reupdate the min distance between index1 and index2 index1, index2 = -1, -1 curr_min = len(words) for i, word in enumerate(words): if word == word1: index1 = i if word == word2: index2 = i if index1 != -1 and index2 != -1: curr_min = min(curr_min, abs(index1 - index2)) return curr_min
Reading Progress
0%